Description
If you search stack overflow you will see many people having the same problem:
(Not my example original)
Example:
I have two models, named Product and Image, which are linked by Product hasMany Image and Image belongsTo Product.
I want to fetch all products with the first image each. I would use this code:
$this->Products->find('all')
->contain([
'Images' => function($q) {
return $q
->order('created ASC')
->limit(1);
}
]);
Looks about right, right? Except now only one of the products contains an image, although actually each product contains at least one image (if queried without the limit).
The resulting Queries
The problem seems to be with the limit, since this produces the following two queries (for example):
SELECT
Products.id AS `Products__id`,
FROM
products Products
and
SELECT
Images.id AS `Images__id`,
Images.product_id AS `Images__product_id`,
Images.created AS `Images__created`
FROM
images Images
WHERE
Images.product_id in (1,2,3,4,5)
ORDER BY
created ASC
LIMIT 1
Looking at the second query, it is quite obvious how this will always result in only one image.
The Problem
However, I would have expected the Cake ORM to limit the images to 1 per product when I called limit(1).
The behaviour feels like bug to me if you are selecting Entities from the table you do not know the total count why would you ever want to limit the total associations?
there is a solution for limiting to 1 of creating a fake hasOne association in the model but for limiting to other numbers is not possible. If this is NOT a bug please show me a simple solution on how to limit hasMany associations as I do not want to have to pull large amounts of data from DB that is not needed.