0

I want to limit the joined results by passing a condition (limit) to ->contain('ProductCategory')

$products = $ProductTable
    ->find('all')
    ->where($where)
    ->contain(
        [
            'ProductPrice' => [
                'ProductPricetier'
            ],
            'ProductCategory' => [
                'sort' => ['ProductCategory.id DESC']
            ]
        ],
        function (Query $q) {
            return $q->limit(1);
        }
    );

throws an exception:

Cannot set containments. To use $queryBuilder, $associations must be a string

How to limit the result of a single association?

ndm
  • 59,784
  • 9
  • 71
  • 110
Jonathan
  • 1,955
  • 5
  • 30
  • 50

1 Answers1

2

I'm not sure if your example was formatted the same way as you've initially posted it, but with proper formatting as I've edited it in you should see that you're not passing the closure as an option for a containment, but as the second argument to the contain() method, which only works when the first argument is a string (as mentioned in the error message), specifically an association alias.

You'd need to do for example:

->contain([
    'ProductPrice' => [
        'ProductPricetier'
    ],
    'ProductCategory' => function (Query $q) {
        return $q
            ->order([
                'ProductCategory.id' => 'DESC'
            ])
            ->limit(1);
    },
]);

or

->contain('ProductCategory', function (Query $q) {
    return $q
        ->order([
            'ProductCategory.id' => 'DESC'
        ])
        ->limit(1);
});

That being said, this is probably not going to work the way you think it is, as the limit in a contain doesn't work on a per row/group basis, instead it will be ignored for belongsTo and hasOne associations, and for hasMany and belongsToMany associations it will be applied to the whole secondary association data query, limiting the overall retrieved associated records, ie it would return only 1 associated record in total, not 1 per row/group.

Check for example How to limit contained associations per record/group? for information on how to limit associations per row/group.

See also

ndm
  • 59,784
  • 9
  • 71
  • 110