如何在laravel中的评论中获取用户对象

问题描述 投票:0回答:1

我正在尝试与用户发布帖子,并发布评论,但我也想要评论用户数据。目前我正在使用此代码获取与post相关的userdata和注释,但也希望用户对象进行注释。我正在使用的代码在PostController.php中

public function index()
{   
    $post=Post::orderBy('created_at','DESC')->with('user')->with('comments' )->get();
    return response()->json(["posts" => $post ]);
}

这是回归

enter image description here

我还在模型中设置了关系有没有办法让我可以在注释对象中获取用户对象,如下所示:

enter image description here

谢谢!

php laravel
1个回答
1
投票

试试这个 :

public function index()
{   
    $post = Post::orderBy('created_at','DESC')with(['comments', 'comments.user'])->get();
    return response()->json(["posts" => $post ]);
}

我希望能帮助你

© www.soinside.com 2019 - 2024. All rights reserved.