Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在laravel中获取注释中的用户对象_Php_Laravel - Fatal编程技术网

Php 如何在laravel中获取注释中的用户对象

Php 如何在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

我正在尝试与用户一起获取帖子,并发布评论,但我还需要评论的用户数据。目前,我用这段代码获取与post相关的userdata和注释,但也希望用户对象提供注释。我正在使用的代码位于PostController.php

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提出了同样的建议,其工作原理如下:)