0

I have relations Postcategory hasMany Posts and Post hasOne User. Here is my code which fetches the posts but I am not able to get users data for each post.

$parents = $postcategories->find('all',[

    'fields'=>['Postcategories.id','Postcategories.name'],

    ])->contain(['Posts'=>function ($q) {
                        return $q->select(['id', 'title','postcategory_id'])
                                ->where(['Posts.active' => 1])
                                ->order('Posts.created DESC')
                                ->limit(5)
                                ;}])
        ->where(['Postcategories.parent_id is null','Postcategories.active'=>1])
        ->hydrate(false)->toArray();

Also I want only 5 latest posts for each category. This code fetches only 5 posts for first category and blank array for remaining categories.

ndm
  • 59,784
  • 9
  • 71
  • 110
  • 1
    You may want to check out **http://stackoverflow.com/q/1442527/1392379**, **http://stackoverflow.com/q/30241975/1392379**, and **http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#passing-conditions-to-contain** – ndm Jun 25 '15 at 13:11
  • I went through this article of book. but no help still not able to get users data for each post. – Chirayubhatt Jun 25 '15 at 13:20
  • I went through this article of book. but no help still not able to get users data for each post. If I remove the function ($q) and add =>['Users'], it gives me correct data but then there is no selection of fields of posts and users. – Chirayubhatt Jun 25 '15 at 13:29
  • Look at the last example that shows the use of the `queryBuilder` option, that's what you have to use if you want to manipulate the query and add additional options for the containment, that way you can simply add the `Users` association name to that array too. – ndm Jun 25 '15 at 14:05
  • Thanks ndm, I used the queryBuilder and that gave me the record set for each Postcategory, I get posts, and for each post I get its author. Now the thing is I need to limit the posts to latest 5 for each post category. – Chirayubhatt Jun 26 '15 at 06:36
  • Duplicate of http://stackoverflow.com/questions/30241975/loading-associated-model-data-in-cakephp3 – José Lorenzo Rodríguez Jun 28 '15 at 07:53

0 Answers0