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