Laravel 5 |多对多关系不起作用
Laravel 5 | Many to Many Relationship not working
我是 laravel5 的新人。
我使用 "Many to Many" 关系来获取基于给定标签的所有消息。
消息模型:
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();
($标签:)
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();
我的输出:
[]
但是我有带有标签 "Public" 的消息。
我的代码有什么问题?
参考:https://laravel.com/docs/5.1/eloquent-relationships#many-to-many
您有任何与给定标签相关的消息吗?
$tag = App\tags::where('name','public')->first();
dd($tag->messages()->get());
在 Message
模型的 tags()
方法中,您还应该提供 messages_tags
枢轴 table 名称(包括 "messages_id" 和 "tags_id") 并访问 messages
你应该使用:
$tag->messages;
或者您可以使用(预加载):
$tag = App\tags::with('messages')->where('name','public')->first();
然后使用:
$tag->messages;
我是 laravel5 的新人。 我使用 "Many to Many" 关系来获取基于给定标签的所有消息。
消息模型:
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();
($标签:)
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();
我的输出:
[]
但是我有带有标签 "Public" 的消息。
我的代码有什么问题?
参考:https://laravel.com/docs/5.1/eloquent-relationships#many-to-many
您有任何与给定标签相关的消息吗?
$tag = App\tags::where('name','public')->first();
dd($tag->messages()->get());
在 Message
模型的 tags()
方法中,您还应该提供 messages_tags
枢轴 table 名称(包括 "messages_id" 和 "tags_id") 并访问 messages
你应该使用:
$tag->messages;
或者您可以使用(预加载):
$tag = App\tags::with('messages')->where('name','public')->first();
然后使用:
$tag->messages;