属性[user]在此集合实例上不存在



我正在开发一个社交应用,前端使用React,后端使用laravel。我试图接收所有的帖子与他们的喜欢,用户,评论。我有这些关系:1/用户模型有多个帖子,帖子模型属于一个用户。2/Post模式有很多人喜欢3/Post模型有多条评论,一条评论属于一个用户。当获得所有帖子返回时,我成功地获得了它的喜欢和用户信息,但对于评论,我想获得用户的评论。所以我做了$posts->comments->user->user_name然后,我得到了错误:属性[user]不存在于此集合实例。但是当我试图获得评论信息时,它正常工作($posts->comments)我在Post模型中的评论关系:

public function comments()
{
return $this->hasMany('AppModelsComment');
}

我在评论模型中的用户关系:

public function user()
{
return $this->belongsTo('AppModelsUser');
}

我的方法在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,它说:属性[user]不存在于这个集合实例上,当我试图只获得评论信息时,它工作了:

'comments' => $this->comments,

请帮忙好吗?和THNX提前。

也许您需要添加关系user()到Post模型?

最新更新