Daniel Faria
Daniel Faria

Reputation: 1484

How to choose the fields from a associated model at find

Before I had this:

//ArticlesController::index
$articles = $this->Articles->find('all', [
  'contain' => ['Comments']
]);

So I set the fields key:

//ArticlesController::index
$articles = $this->Articles->find('all', [
  'fields' => ['title', 'text],
  'contain' => ['Comments']
]);

Since I set the fields key the result of the find is not bringing the comments anymore.

Upvotes: 1

Views: 62

Answers (1)

Alex Stallen
Alex Stallen

Reputation: 2252

$articles = $this->Articles->find('all')
        ->select(['fields_you_want_from_Articles'])
        ->contain(['Comments'  => function($q) {
            return $q
                ->select(['fields_you_want_from_Comments']);
        }]);

Upvotes: 1

Related Questions