英文:
How to select columns of a model together with those of it's relationship
问题
Controller
$articles = Article::with('tags')->latest()->get();
Blade
@foreach($articles as $article)
<h2>{{ $article->title }}</h2>
@foreach($article->tags as $tag)
<span>{{ $tag->name }}</span>
@endforeach
<hr>
@endforeach
上面的代码是有效的。现在,我想从模型中仅选择一些列。
我尝试了以下方法,但现在标签的名称不显示,也没有收到任何错误消息。
$articles = Article::select(['title', 'created_at', 'body', 'slug'])->with(['tags' => function ($query) {
$query->select('name');
}])->latest()->get();
英文:
Controller
$articles = Article::with('tags')->latest()->get();
Blade
@foreach($articles as $article)
<h2>{{ $article->title }}</h2>
@foreach($article->tags as $tag)
<span>{{ $tag->name }}</span>
@endforeach
<hr>
@endforeach
The above works. Now, I'd like to select just some columns from the models.
I have tried the following but now the names of the tags are not displayed and not getting any error.
$articles = Article::select(['title', 'created_at', 'body', 'slug'])->with(['tags' => function ($query) {
$query->select('name');
}])->latest()->get();
答案1
得分: 1
Laravel的预加载系统支持加载仅限于某些列。
https://laravel.com/docs/10.x/eloquent-relationships#eager-loading-specific-columns
$articles = Article::select(['id', 'title', 'created_at', 'body', 'slug'])
->with('tags:id,name')
->latest()
->get();
(通常,您会希望确保包括 `id`,否则会有些问题。)
英文:
Laravel's eager loading system supports loading only some columns.
https://laravel.com/docs/10.x/eloquent-relationships#eager-loading-specific-columns
$articles = Article::select(['id', 'title', 'created_at', 'body', 'slug'])
->with('tags:id,name')
->latest()
->get();
(You'll typically want to ensure you include id
, or things get a little wonky.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论