Laravel Eloquent hasMany relationship
Hi I am new to Laravel and currently in am using Laravel 4.2. I am trying to create an application where I have users, posts and comments table and have the following model
User Model
function posts() {
return $this->hasMany('Post');
}
function comments(){
return $this->hasMany('Comment');
}
Post Model
function users() {
return $this->belongsTo('User');
}
function comments() {
return $this->hasMany('Comment');
}
Comment Model
function posts(){
return $this->belongsTo('Post');
}
function users(){
return $this->belongsTo('User');
}
What I want to achieve :
user's Post and comment for Post
eg:: User1 -> Post one -> comment for post one
What I have done So far:::
$user = User::find(1);
$post = $user->posts()->get();
I am able to get post but how do i get comment for specific post??
Update
Thanks to @Bogdan for his help I am able to get post and comment for user. But as usual had another problem.
What I got:
foreach($user->post AS $post) {
foreach ($post->comment AS $comment ) {
$comment->commentcontent; $user->uername;
}
}//first foreach
This is what I get
comment one by user1.
comment two by user1.
But in reality comment one is created by user1 and comment two is created by user2.
Thank you for your help in advance. Can post full code if needed.
When you retrieve a users' posts with $user->posts()->get()
you get a Collection
of Models
, on which you can use find
to get the specific post you want. Then you can retrieve the post's comment the same way you retrieved the users' posts:
$user = User::find(1);
$post = $user->posts()->find($postId);
$comments = $post->comments;
If you want to iterate over the entire posts collection, you can do this and access comments for each post individually, without filtering for a specific post:
foreach ($user->posts as $post)
{
$comments = $post->comments;
}
Also, for future reference, accesing the relation as a property will return a Collection, while accessing the relation as a method will return a Query Builder instance. So $user->posts
is the same as $user->posts()->get()
.
You want to get user that made the comment, so get that user from the comment object.
Try this
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}