Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 5 使用laravel在hasMany关系中用外键覆盖主键_Laravel 5_Eloquent - Fatal编程技术网

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

Laravel 5 使用laravel在hasMany关系中用外键覆盖主键,laravel-5,eloquent,Laravel 5,Eloquent,这是我的桌子 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(); } 现在我怎

这是我的桌子

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。

在您的post模型中:

   public function comments()
    {
      return $this->hasMany('App\Model\Comment');
    }
在您的Post控制器中:

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);
}
在您的帖子模型中:

   public function comments()
    {
      return $this->hasMany('App\Model\Comment');
    }
在您的Post控制器中:

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