首页 > 解决方案 > 使用 laravel 在 hasMany 关系中用外键覆盖主键

问题描述

这是我的桌子

Posts

id | name | created_At

Comments

id | comment | post_id | created_at

后模型

function comments(){
      return $this->hasMany('App\Models\Comment','id','post_id');
 }

帖子控制器

function index()
{
    Post::with('comments')::get();
}

现在我怎样才能得到所有帖子的列表以及评论?

我正在尝试匹配子表中的 post_id。

标签: laravel-5eloquent

解决方案


在您的帖子模型中:

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

在您的后期控制器中:

use Illuminate\Http\Request;

function index(Request $request)
{
    $posts=Post::with('comments')->get();

    // in json
    return response()->json($posts);

    // in your view
    //return view('viewname')->with('posts',$posts);
}

推荐阅读