发布模型
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
public function users()
{
return $this->belongsTo('App\User');
}
评论模型
class Comment extends Model
{
public function posts()
{
return $this->belongsTo('App\Post');
}
}
用户模型
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
现在我的问题是如何访问属于带有评论用户名的帖子的所有评论 预先感谢您
最佳答案
试试这个,它将返回所选用户的所有带有评论的帖子以及带有作者的帖子。
$data = User::with('post.comment')
-> with('post.author')
-> Where('id',$user_id)
-> first();
这将获取作者的帖子以及发表评论的用户的评论。 假设您的模型是这样设置的,
Post belongs to an Author,
Author has many Post,
Post has many Comment
Comment belongs to a Post
Comment belongs to a User
User has many Comment.
$posts = Post::with('author') -> with('comment.user') -> get();
关于php - 如何从关系中检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32391723/