I'm new in laravel5. I use "Many to Many" Relationships to get all messages based on the given tag.
MESSAGE MODEL :
function tags(){
return $this->belongsToMany('App\tags')->withTimestamps();
}
TAGS MODEL :
public function messages() {
return $this->belongsToMany('App\messages', "messages_tags", "messages_id", "tags_id");
}
MY INPUT :
$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",
}
I tried to get Messages with Tag.
$tag->messages()->get();
MY OUTPUT :
[]
But i have messages with the Tag "Public".
What is Wrong with my code ?
In your Message
model in the tags()
method you should provide the messages_tags
pivot table name as well (including "messages_id" and "tags_id") and to access the messages
you should use:
$tag->messages;
Or you may use (Eagre loading):
$tag = App\tags::with('messages')->where('name','public')->first();
Then use:
$tag->messages;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments