Php 如何在laravel中获取注释中的用户对象
我正在尝试与用户一起获取帖子,并发布评论,但我还需要评论的用户数据。目前,我用这段代码获取与post相关的userdata和注释,但也希望用户对象提供注释。我正在使用的代码位于PostController.phpPhp 如何在laravel中获取注释中的用户对象,php,laravel,Php,Laravel,我正在尝试与用户一起获取帖子,并发布评论,但我还需要评论的用户数据。目前,我用这段代码获取与post相关的userdata和注释,但也希望用户对象提供注释。我正在使用的代码位于PostController.php public function index() { $post=Post::orderBy('created_at','DESC')->with('user')->with('comments' )->get(); return response
public function index()
{
$post=Post::orderBy('created_at','DESC')->with('user')->with('comments' )->get();
return response()->json(["posts" => $post ]);
}
这又回来了
我还设置了模型中的关系
是否有任何方法可以在comments对象中获取用户对象,如下所示:
谢谢 试试这个:
public function index()
{
$post = Post::orderBy('created_at','DESC')with(['comments', 'comments.user'])->get();
return response()->json(["posts" => $post ]);
}
我希望能帮助您您需要在您的评论模型中设置相同的用户关系,然后使用
和(['comments','comments.user'])
您好,谢谢!是的,谢谢@aynber提出了同样的建议,其工作原理如下:)