我是Laravel的新手并且正在做一个构建迷你社交网络app的项目。我有一个与用户模型有关系的帖子模型。 我有一个帖子页面,只有经过身份验证的用户和他/她的朋友的帖子才会显示。在我的PostController中,我查询了经过身份验证的用户的朋友,就像这样;
$friends = Auth::user()->friends();
之前在我友好的特性中定义了friends()对象。这很好,如屏幕截图所示。 我试图查询其user_id是经过身份验证的用户或朋友的用户的帖子,如此
$posts = Post::where('user_id', $user->id)
->where('user_id', $friends->id)
->get();
但不断收到错误
此集合实例上不存在Property [id] ...
答案 0 :(得分:1)
$friends = Auth::user()->friends();
现在$friends
是一个集合,其中包含一组用户,请注意$friends
不包含名为id
的变量,而是包含集合中的每个项目(用户对象) )包含一个id。
这是您收到错误的地方 - ->where('user_id', $friends->id)
(此处$friends
没有ID)
所以首先我们取出所有朋友的ids,然后拿出朋友们发的帖子。
$friends = Auth::user()->friends();
$friends_id = $friends->pluck('id'); //we have all friends id as an array
$posts = Post::where('user_id', $user->id)
->whereIn('user_id', $friends_id)
->get();