使用laravel在hasMany关系中使用外键覆盖主键

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用laravel在hasMany关系中使用外键覆盖主键相关的知识,希望对你有一定的参考价值。

这是我的表格

Posts

id | name | created_At

Comments

id | comment | post_id | created_at

发布模型

function comments(){
      return $this->hasMany('AppModelsComment','id','post_id');
 }

PostsController

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

现在我如何获得所有帖子的列表以及评论?

我想在子表中匹配post_id。

答案

在你的帖子模型中:

   public function comments()
    {
      return $this->hasMany('AppModelComment');
    }

在你的帖子控制器中:

use IlluminateHttpRequest;

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

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

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

以上是关于使用laravel在hasMany关系中使用外键覆盖主键的主要内容,如果未能解决你的问题,请参考以下文章