How do I write a model in CakePHP 2 for 3 joined mysql tables

45 views Asked by At

I have a problem understanding how I'm supposed to write my model in CakePHP 2.x for this scenario:

I have a table « orders » that has many products in « products » table. This product table has a « size » table.

This mysql query shows what I want to get out of my model. I know how to do a model for the « orders » and « products » tables but I don't understand how to also include the « size » table.

SELECT 
orders.id, 
orders.name, 
products.id, 
products.name, 
sizes.id, 
sizes.name
FROM
orders 
INNER JOIN products ON orders.id = products.order_id
INNER JOIN sizes ON sizes.id = products.size_id
1

There are 1 answers

0
flaggalagga On

I did not find a solution in CakePHP - How do I join a table on a joined table?

I did like this :

 $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));

 $this->request->data = $this->Order->find('first', $options);

 $options = array('conditions' => array('Product.order_id' => $id));

 $Products= $this->Order->Product->find('all', $options);

From there I would get in the array my size for that product:

[Size] => Array
    (
        [id] => 1
        [name] => 'BIG'
    )