我的数据库中有4个表:posts
,categories
,tags
和relation_with_tag_category
在我的Post模型中,我有一个'belongsToMany'关系:
public function categories(){
return $this->belongsToMany('App\Category', 'category_relation')->withTimestamps();
}
public function tags(){
return $this->belongsToMany('App\Tag', 'category_relation')->withTimestamps();
}
如何通过上面解释的相同表格与帖子,标签和类别建立关系,如何在我的刀片视图中显示?
它就像wordpress术语关系
假设你的关系正常(我不知道我是否只看到一个模型关系)你可以使用with函数查询你的表。
$myPosts = Post::with(['categories','tags'])->get();
并像这样使用它们
$myPosts->categories->all();
$myPosts->tags->all();