P
P
photosho2016-03-12 14:23:23
Laravel
photosho, 2016-03-12 14:23:23

How to eagerly get the title of a related article?

Hello. Faced such problem: it is necessary, using eager loading in Laravel, to receive the list of comments and headings of the materials connected with them. The comment is related to several material types by the morphTo relationship. I do it like this:

$comments = Comment::with(['material' => function($query) {
  $query->selectRaw('title');
}])->orderBy('id', 'desc')->take(15)->get();

As a result, I get the downloaded comments along with the full versions of the materials (all fields). What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
miki131, 2016-03-13
@miki131

$query->select(['id', 'title']);
id is needed to link models

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question