如何选择模型的列以及它的关联列

huangapple go评论68阅读模式
英文:

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(&#39;tags&#39;)-&gt;latest()-&gt;get();

Blade

@foreach($articles as $article)
    &lt;h2&gt;{{ $article-&gt;title }}&lt;/h2&gt;
    
    @foreach($article-&gt;tags as $tag)
        &lt;span&gt;{{ $tag-&gt;name }}&lt;/span&gt;
    @endforeach
    
    &lt;hr&gt;
@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([&#39;title&#39;, &#39;created_at&#39;, &#39;body&#39;, &#39;slug&#39;])-&gt;with([&#39;tags&#39; =&gt; function ($query) {
      $query-&gt;select(&#39;name&#39;);
    }])-&gt;latest()-&gt;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([&#39;id&#39;, &#39;title&#39;, &#39;created_at&#39;, &#39;body&#39;, &#39;slug&#39;])
    -&gt;with(&#39;tags:id,name&#39;)
    -&gt;latest()
    -&gt;get();

(You'll typically want to ensure you include id, or things get a little wonky.)

huangapple
  • 本文由 发表于 2023年6月14日 23:45:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定