我正在开发一个在前端使用 React 并在后端使用 laravel 的社交应用程序。我正在尝试接收所有带有他们喜欢、用户和评论的帖子。我有这些关系:1/用户模型有很多帖子,帖子模型属于一个用户。2/ Post 模型有很多赞 3/ Post 模型有很多评论,一个评论属于一个用户。当恢复所有帖子时,我成功地获得了它的喜欢和用户信息,但对于评论,我想获得用户的评论。所以我做了 $posts->comments->user->user_name 然后,我得到了错误:Property [user] does not exist on this collection instance。但是当我试图获取评论信息时,它工作正常($posts->comments)我在 Post 模型中的评论关系:
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
我在评论模型中的用户关系:
public function user()
{
return $this->belongsTo('App\Models\User');
}
当我尝试获取所有帖子时,我在 PostController 中的方法:
public function allPosts()
{
$posts = Post::with('user','likes','comments')->get();
if($posts->count() < 1) {
return response()->json([
'success' => false,
'message' => 'There are no posts!'
]);
}else {
return response()->json([
'success' => true,
'data' => PostResource::collection($posts),
'message' => 'Succefully retreived all posts!'
]);
}
}
正如您注意到我通过资源发送数据,所以我的 PostResource 的方法:
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'user_id' => $this->user_id,
'content' => $this->content,
'image_path' => $this->image_path,
'user' => $this->user,
'likes' => $this->likes->count(),
'isLiked' => $this->likes->where('user_id', auth()->user()->id)->isEmpty() ? false : true,
'comment_user' => $this->comments->user->user_name,
'created_at' => $this->created_at->format('d/m/y'),
'updated_at' => $this->updated_at->format('d/m/y')
];
}
正如我所说,一切都很好,只是对于comment_user它说:这个集合实例上不存在属性[用户],当我试图只获取评论信息时它起作用了:
'comments' => $this->comments,
请问有什么帮助吗?和thnx提前。