如何在 laravel/php 中访问此集合的内容
How to access the contents of this collection in laravel/php
我是 Laravel 的新手,正在做一个构建迷你社交网络的项目 app.I 有一个与用户模型有关系的 post 模型。
我有一个 Post 页面,其中只有经过身份验证的用户和 his/her 朋友的 post 会显示。在我的 Post 控制器中,我像这样查询经过身份验证的用户的朋友;
$friends = Auth::user()->friends();
friends() 对象先前已在我的友好特征中定义。如屏幕截图所示,效果很好。
我试图查询 post 的 user_id 是经过身份验证的用户或朋友的 post ,例如
$posts = Post::where('user_id', $user->id)
->where('user_id', $friends->id)
->get();
但一直报错
Property [id] does not exist on this collection instance…
该合集在屏幕截图中显示为死机。我如何遍历并获取所有朋友的 ID 数组。
$friends = Auth::user()->friends();
现在 $friends
是一个集合,其中包含用户的集合,请注意 $friends
不包含名为 id
的变量,而是集合中的每个项目(用户对象)包含一个 id。
这是你得到错误的地方 - ->where('user_id', $friends->id)
(这里 $friends
没有 id)
所以我们先把所有好友的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();
我是 Laravel 的新手,正在做一个构建迷你社交网络的项目 app.I 有一个与用户模型有关系的 post 模型。 我有一个 Post 页面,其中只有经过身份验证的用户和 his/her 朋友的 post 会显示。在我的 Post 控制器中,我像这样查询经过身份验证的用户的朋友;
$friends = Auth::user()->friends();
friends() 对象先前已在我的友好特征中定义。如屏幕截图所示,效果很好。 我试图查询 post 的 user_id 是经过身份验证的用户或朋友的 post ,例如
$posts = Post::where('user_id', $user->id)
->where('user_id', $friends->id)
->get();
但一直报错
Property [id] does not exist on this collection instance…
该合集在屏幕截图中显示为死机。我如何遍历并获取所有朋友的 ID 数组。
$friends = Auth::user()->friends();
现在 $friends
是一个集合,其中包含用户的集合,请注意 $friends
不包含名为 id
的变量,而是集合中的每个项目(用户对象)包含一个 id。
这是你得到错误的地方 - ->where('user_id', $friends->id)
(这里 $friends
没有 id)
所以我们先把所有好友的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();