我是laravel5的新手。我使用"多对多"关系来获取基于给定标签的所有消息。
消息模型 :
function tags(){
return $this->belongsToMany('App'tags')->withTimestamps();
}
标签型号 :
public function messages() {
return $this->belongsToMany('App'messages', "messages_tags", "messages_id", "tags_id");
}
我的输入 :
$tag = App'tags::where('name','public')->first();
($tag :)
App'tags {#681
id: "5",
name: "Public",
created_at: "2016-02-10 13:51:36",
updated_at: "2016-02-10 08:21:36",
}
我尝试获取带有标签的消息。
$tag->messages()->get();
我的输出 :
[]
但是我有带有"公共"标签的消息。
我的代码有什么问题?
在Message
模型中的 tags()
方法中,您还应该提供messages_tags
数据透视表名称(包括"messages_id"和"tags_id"),并且要访问messages
您应该使用:
$tag->messages;
或者您可以使用(Eagre 加载):
$tag = App'tags::with('messages')->where('name','public')->first();
然后使用:
$tag->messages;
参考:https://laravel.com/docs/5.1/eloquent-relationships#many-to-many
您有任何与给定标签相关的消息吗?
$tag = App'tags::where('name','public')->first();
dd($tag->messages()->get());