Example we have two tables, one is articles and another is comments table. Articles hasMany relations with comments.
Example our articles table looks like
articles
id | title | created | modifier
Comments
Id | comment | article_id | created | modified
Assuming in articles table we have build a hasMany relation with comments like below example
$this->hasMany('Comments', [ 'foreignKey' => 'article_id', ]);
Here, article_id is the foreign key.
Now, in the ArticlesController/index method we will write a query where we want only the last two comments.
So, we can write our index method like below
public function index() { $article = $this->Articles->find() ->contain('Comments', function($q){ return $q ->limit(2) ->order(['Comments.created' => 'DESC']); } ); $this->set(compact('articles')); }
So now in view you will get articles with 2 recent comments.