[英]Laravel Pivot Relationship
我正在使用Laravel 5.7,我有下表
类别
id | category_name
后类别
id | category_id | post_id | some other fields
帖子
id | post_title
我已经属于类别Model中的许多关系
public function post(){
return $this->belongsToMany(Post::class,'post_categories','category_id','post_id')
->withPivot('col2', 'col3','col4');
}
$response=Category::with('post')->get();
这将返回预期的结果,但现在我不需要在响应中添加类别详细信息,这意味着可以在数据透视模型中声明关系,因为我知道category_id并且可以避免在响应中使用类别详细信息
我的目的是按类别ID检索所有帖子
您可以在“类别”上使用select()
函数来删除不必要的列。
请注意,类别表的“ id”很重要,因为它在数据透视表中用作外键。
// this will only get the id of the category
// and all the post and pivot data.
$response = Category::select('id')->with('post')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.