[英]How to access the contents of this collection in laravel/php
我是Laravel的新手,正在做一个构建迷你社交网络应用程序的项目。我有一个与用户模型有关系的帖子模型。 我有一个帖子页面,其中仅显示经过身份验证的用户及其朋友的帖子。 在我的PostController中,我像这样查询经过身份验证的用户的朋友;
$friends = Auth::user()->friends();
在我的友好特征中先前定义了friends()对象的位置。 如屏幕截图所示,效果很好。 我试图查询user_id是经过身份验证的用户或朋友的user_id的帖子,例如
$posts = Post::where('user_id', $user->id)
->where('user_id', $friends->id)
->get();
但是不断出错
属性[id]在此集合实例上不存在...
$friends = Auth::user()->friends();
现在$friends
是一个集合,其中包含用户集合,请注意, $friends
不包含名为id
的变量,而是collection中的每个项目(User对象)都包含一个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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.