Php 如何从关系中检索数据?

Php 如何从关系中检索数据?,php,Php,后期模型 class Post extends Model { public function comments() { return $this->hasMany('App\Comment'); } public function users() { return $this->belongsTo('App\User'); } class Comment extends Model {

后期模型

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');
    }
评论模式

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');
    }
用户模型

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(); 

您可以查询注释关系,如下所示:

$post_id = 7;
$username = 'username';

$comments = Comment::where('post_id', $post_id)->whereHas('user', function($q) use($username) {
    $q->where('username', $username);
})->get();

由于只有用户名,您只能获得给定用户拥有的所有帖子的所有评论,因此您可以使用hasManyThroughrelation@zakius.thank你能发布你的答案吗?试试这个
user::with('post.comment')->get()
@mdamia.thank you.是否可以在单个查询中访问。我需要显示带有作者姓名的帖子内容,所有评论都属于带有用户名的帖子。我将发布一些内容作为答案,试一试。我的要求是。我需要显示带有作者姓名的帖子,以及带有注释用户名的属于该帖子的注释。如果你看到我的表结构,我正在存储注释用户idkey@madamia.i正确地获取集合对象。但在最后,我得到了错误,比如哎呀,看起来好像出了什么问题。Builder.php第2025行中的1/1 BadMethodCallException:调用未定义的方法Illumb\Database\Query\Builder::user()\@vision检查
user
方法是否已定义