I have the following database tables: elements, users, groups, itemImages. Between relations (elements, groups) and (users, groups) there are many different relations, and between them (between points, itemImages). All relevant foreign keys were installed in CakePHP as associations.
How can I build a query with the contains () function that selects all the elements and their main image that are in the group that was assigned as the main group for the user with a specific identifier?
To make it clearer, here's what a simple SQL query looks like:
SELECT items.id AS itemId, items.name, itemImages.url AS itemUrl FROM items INNER JOIN groups_items ON groups_items.item_id = items.id INNER JOIN groups ON groups_images.group_id = groups.id INNER JOIN groups_users ON groups_users.group_id = groups.id INNER JOIN users ON groups_users.user_id = users.id INNER JOIN itemImages ON itemImages.item_id = items.id WHERE groups_users.isMainGroup = 1 AND users.id = :userId AND itemImages.isMainImage = 1
CakePHP code that I have:
$items = $this->Items->find() ->hydrate(false) ->contain([ 'Groups.Users' => function($q) use ($userId){ return $q->where(['isMainGroup' => 1, 'Users.id' => $userId]); }, 'ItemImages' => function($q){ return $q->where(['isMainImage' => 1]); }, ]);
user1507558
source share