首页 > 解决方案 > 在 Laravel 中使用 Eager Loading 查询构建器 Eloquent

问题描述

有一个典型的带有帖子和评论的 squeme,其中一个帖子有很多评论,一个评论属于一个帖子:

岗位型号:

 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

标签: sqllaraveleloquent

解决方案


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

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();

注意:未经测试。


推荐阅读