Reputation: 1783
I have these Models:
class Post extends Model
{
protected $primaryKey = 'post_id';
public function comments()
{
return $this->hasMany(Comment::class, 'post_id', 'post_id');
}
}
class Comment extends Model
{
protected $primaryKey = 'comment_id';
public function post()
{
return $this->belongsTo(Post::class, 'post_id');
}
}
class User extends Authenticatable
{
protected $primaryKey = 'user_id';
public function comments()
{
return $this->hasMany(Comment::class, 'user_id', 'commenter_id');
}
}
class MyController extends Controller
{
public function post($id = null)
{
$post = Post::where('post_id', $id)->first();
$comments = $post->comments;
}
}
What I want is to get the user of each comment something like $post->comments->user
in order to get the user information easy like below:
@foreach($post->comments as $comment)
{{ $comment->user->first_name.' '.$comment->user->last_name }}
@endforeach
How can I do this? I guess I need something named hasManyThrough
but it's too complex and I got confused :|
Upvotes: 1
Views: 1347
Reputation: 151
Just create function in your Comment model which must return relation like this
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
And then call this function on your comment object
Upvotes: 0
Reputation: 64476
Yes you can get the user object with comment object, using
$post = Post::with('comments.user')->where('post_id', $id)->first();
and define mapping for user in comments models
class Comment extends Model
{
protected $primaryKey = 'comment_id';
public function post()
{
return $this->belongsTo(Post::class, 'post_id');
}
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
Upvotes: 2