Say I have two models, named Product and Image, which are linked by Product hasMany Image and Image belongsTo Product.
Now, say 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 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.
However, I would have expected the Cake ORM to limit the images to 1 per product when I called limit(1).
My question: Is this an error in how I use the ORM? If so, how should I limit the number of images to one per image?
The cleanest way you can do this is by creating another association:
$this->hasOne('FirstImage', [
    'className' => 'Images',
    'foreignKey' => 'image_id',
    'strategy' => 'select',
    'sort' => ['FirstImage.created' => 'DESC'],
    'conditions' => function ($e, $query) {
        $query->limit(1);
        return [];
    }
])
                        Check it ,this one is my code
 $this->Orders->hasOne('Collections', [
                    'className' => 'Collections',
                    'foreignKey' => 'order_id',
                    'strategy' => 'select',
                    'conditions' => function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) {
                    $query->order(['Collections.id' => 'ASC']);
                    return [];
                                                                                                                         }
                    ]);
                    $Lists = $this->Orders->find('all')->where($condition)->contain(['Collections'])->order(['Orders.due_date DESC']);
                    $this->set(compact('Lists'));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With