查询构建器雄辩地使用Laravel中的Eager Loading

时间:2018-12-10 17:33:06

标签: sql laravel eloquent

一个典型的带有帖子和评论的区域,其中一个帖子包含很多评论,而评论属于一个帖子:

发布模型:

 public function comments(){
    return $this->hasMany('App\Comment');
}

迁移后

Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');         
    });

评论模型:

 public function Post(){
    return $this->belongsTo('App/Post', 'id');
}

评论迁移:

   Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->date('date_comment');
        $table->unsignedInteger('post_id')->nullable()->default(null);
        $table->foreign('post_id')->references('id')->on('posts');
        });

我想在Laravel中使用紧急加载。

例如。如何通过急切加载获取 最新评论的所有帖子

我尝试过:

$post = Post::with('comments:post_id, date_comment')->get();

但是这样我得到了所有评论。有什么帮助吗?

最诚挚的问候

编辑:

foreach语句(刀片):

   @foreach($posts as $post)            
            <td>{{ $post->name }}</a></td>
            <td>
            {{ !empty($post->comments[0]) ? $post->comments[0]-> 
                date_comment : '' }}
            </td>                                      
   @endforeach

2 个答案:

答案 0 :(得分:2)

您需要再建立一种关系才能检索最新评论。

Post.php

public function comments(){
    return $this->hasMany('App\Comment');
}

public function latestComment(){
    return $this->hasOne('App\Comment')->orderBy('date_comment', 'desc');
}

现在您可以像这样检索它。

$posts = Post::with('latestComment')->get();

注意:未经测试。

答案 1 :(得分:1)

您可以constrain eager load

$posts = Post::with(['comments' => function($qry) {
    $qry->->select('id','date_comment')->orderBy('date_comment', 'desc')->first();
}])->get();

使用此功能,您可以访问所有带有最新评论的帖子

如果对查询使用select方法,请不要忘记在列表中添加id字段。

要访问date_comment条评论:

foreach($posts as $post) {
    var_dump(!empty($post->comments[0]) ? $post->comments[0]->date_comment : '');
}