[英]laravel - How can I get the user information of each comment
我有这些模型:
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;
}
}
我想要的是让每个评论的用户像$post->comments->user
这样的东西,以便像下面这样轻松获取用户信息:
@foreach($post->comments as $comment)
{{ $comment->user->first_name.' '.$comment->user->last_name }}
@endforeach
我怎样才能做到这一点? 我想我需要一个名为hasManyThrough
东西,但它太复杂了,我很困惑:|
是的,您可以使用注释对象获取用户对象,使用
$post = Post::with('comments.user')->where('post_id', $id)->first();
并在评论模型中为用户定义映射
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');
}
}
只需在您的 Comment 模型中创建函数,该函数必须返回这样的关系
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
然后在您的评论对象上调用此函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.