Search code examples
relationshipcakephp-3.0

Cakephp database associations


I have 3 tables in database:
Cakephp 3.

Cars{id, type_id,....}
Types{id, name,....}
Images{id, type_name,image_url,....}

And in model cars i would like to set relation to images, actually model associations. I need to fetch image_url from images, with value type_id which is the same in table Cars and in table Images. It means I can forget table Types. Now I am fetching Images with join query from controller, but I would like to associate those models.

Query in controller looks like:

$query->join(['table' = 'Images',
'alias' => 'i',
'conditions' => 'Cars.type_id = i.type_id'
]);

This is relation type: 1 car can have 1 or more images, and 1 image can belong to 1 or many cars. It means M:M. It should be relation belongsToMany. I try to set different relations option, from hasMany to belongsToMany it does not work. Is it possible to do this at all, or it maybe isn't because one table does not contain primary key of another, and I am forced to use join query in controller?

Thank you for advice.


Solution

  • added contain with "recursion" in query:

    $query->contain(['Cars','Types' => ['Images']]);
    

    and i get what i needed. best regards