Limiting Association inside get function

Any way to limit associations inside get function?

$user = $this->Users->get($id, [
‘contain’ => [‘Articles’],
‘limit’ => 5 // isn’t working
]);

See cakephp - How to limit contained associations per record/group? - Stack Overflow
and cakephp - Using limit() on contained model - Stack Overflow

Thanks but those solutions didn’t work. Plus some of those are CakePHP 2 version.

The first link given is pretty much the canonical answer to this question, so if it didn’t work, it seems likely that it’s a problem with how you’ve implemented it. Share what you ended up with by following that answer and maybe we can spot where you’ve gone wrong?


In Users::view action. I’m trying to load the assocciated articles and limit them to only 5 records.

There’s no reason why what you’ve tried would work. What I think you’re trying to do is

'contain' => ['Articles' => ['limit' => 5]]

but that’s not supported. In the first link that Kevin gave, ndm has provided 6 possible solutions for this. What you’ve written here is nothing like any of them.

Yeah at first I tried:

‘contain’ => [‘Articles’ => [‘limit’ => 5]]. But it didn’t work. Going back to the docs get() function has ‘limit’ method and that’s exactly what I was trying in the code you see.

What ndm provided for hasMany scenario is a library solution

$this->hasMany(‘associatedTable’)
->setLimit(5);
And I don’t want to add that library to my project to only achieve this goal.

Any solution I tried and didn’t work I remove it that’s why the code is nothing like what ndm has provided.

Keep reading there. He provided a library solution, two different strategies using select, one using join, one using window functions, and one with a bit of a brute force method. If none of these options are acceptable to you, then you’re probably going to need to submit a PR to Cake which adds direct support for the functionality you want, and hope it gets accepted.

1 Like

Hi @Lamine ,

You can try using the strategy_select option.

https://api.cakephp.org/4.4/class-Cake.ORM.Association.html#STRATEGY_SELECT

1 Like