On Mon, Oct 18, 2010 at 11:02 AM, Dan <[email protected]> wrote:
> Hi,
>
> I am trying out CakePHP on an existing (and messy) website to see if
> it is going to be beneficial to use it for the new features from now
> on. I have been creating a test model that allows admin to search
> through users based on various fields (userId, name, email address,
> orderId).
>
> I have 3 tables that are being used for this:
> Users
> Customers
> Orders
>
> Users links to Customers on a 1 to 1 relationship on 'userId',
> Customers links to Orders on a 1 to many relationship on 'customerId'.
>
> The search feature is working correctly, except that I can't figure
> out how to set conditions on the Orders table.
> This is the query I would write normally to get the user who placed a
> certain order:
>
> SELECT * FROM users u
> LEFT JOIN customers c ON u.userId = c.userId
> LEFT JOIN orders o ON o.customerId = c.customerId
> WHERE o.orderId = $orderId.
>
> I have set up models for Users, Customers and Orders, With 'Users
> $hasOne ' referencing Customers, and 'Customers $hasMany' referencing
> Orders.
>
> If the conditions only reference the Users table, the script brings
> out the Orders data correctly, but I can't get it to allow me to
> search for an orderId, as Orders is referenced by Users through
> Customers.
I think it would make more sense to search by order_id from the
CustomersController, as the Order is directly asociated with Customer.
You CAN do it from User but it seems less elegant. But you can easily
fetch the User info as well if runningfind() from Customer or Order..
In fact, I'd likely put this in Order model. But, if in Customer
model)
public function fetchByOrderId($order_id = null)
{
return $this->Order->find(
'first',
array(
'conditions' => array(
'Order.id' => $order_id
),
'contain' => array(
'Customer' => array(
'User'
)
)
)
);
}
If you were to run the same find from within the controller, it'd be
$this->Customer->Order->find(...). But it's usually a better idea to
put most of your code in the model. So, with above, $data =
$this->Customer->fetchByOrderId($order_id);
If in Order model:
public function fetch($id = null)
{
return $this->find(
'first',
array(
'conditions' => array(
'Order.id' => $order_id
),
'contain' => array(
'Customer' => array(
'User'
)
)
)
);
}
Note that I'm using the ContainableBehavior here. I recommend it, as
it allows for more control on which data you're fetching than working
with 'recursive' option. For that reason, I generally set it in
AppModel's $actsAs array.
Check out the new CakePHP Questions site http://cakeqs.org and help others with
their CakePHP related questions.
You received this message because you are subscribed to the Google Groups
"CakePHP" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected] For more options, visit this group at
http://groups.google.com/group/cake-php?hl=en