我是 Laravel 的新手,正在做一个构建迷你社交网络应用程序的项目。我有一个与用户模型有关系的帖子模型。
我有一个帖子页面,其中仅显示经过身份验证的用户及其朋友的帖子。在我的 PostController 中,我像这样查询经过身份验证的用户的朋友;
$friends = Auth::user()->friends();
Friends() 对象之前已在我的 Friendsable 特征中定义。如屏幕截图所示,效果很好。
我尝试查询 user_id 是经过身份验证的用户或朋友的帖子,如下所示
$posts = Post::where('user_id', $user->id)
->where('user_id', $friends->id)
->get();
但不断出现错误
此集合实例上不存在属性 [id]...
The collection is shown as die-dumped on the screen-shot. How can I iterate over and get an array of the id’s of all the friends.
$friends = Auth::user()->friends();
now the $friends
是一个集合,里面包含了用户的集合,请注意$friends
不包含名为的变量id
相反,集合中的每个项目(用户对象)都包含一个 id。
这是你收到错误的地方 -->where('user_id', $friends->id)
(here $friends
没有身份证)
所以我们首先取出所有好友的id,然后取出好友发的帖子。
$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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)