[英]How to access the contents of this collection in laravel/php
I am new to Laravel and doing a project to build a mini-social network app.I have a post model that has a relationship with the user model. 我是Laravel的新手,正在做一个构建迷你社交网络应用程序的项目。我有一个与用户模型有关系的帖子模型。 I have a Post page, where only the posts of the authenticated user and his/her friends will show.
我有一个帖子页面,其中仅显示经过身份验证的用户及其朋友的帖子。 In my PostController, i queried for the friends of the authenticated user like so;
在我的PostController中,我像这样查询经过身份验证的用户的朋友;
$friends = Auth::user()->friends();
Where the friends() object has earlier been defined in my friendable trait. 在我的友好特征中先前定义了friends()对象的位置。 That works well as shown in the screen shot.
如屏幕截图所示,效果很好。 I tried to query for the posts whose user_id is that of the authenticated user or that of the friends, like so
我试图查询user_id是经过身份验证的用户或朋友的user_id的帖子,例如
$posts = Post::where('user_id', $user->id)
->where('user_id', $friends->id)
->get();
but keep getting an error 但是不断出错
Property [id] does not exist on this collection instance…
属性[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.
我如何遍历并获取所有朋友的ID数组。
$friends = Auth::user()->friends();
now the $friends
is a collection, which contains a collection of users, please note that $friends
does not contain a variable named id
rather the each item in collection(The User object) contains an id. 现在
$friends
是一个集合,其中包含用户集合,请注意, $friends
不包含名为id
的变量,而是collection中的每个项目(User对象)都包含一个id。
This is where you get the error - ->where('user_id', $friends->id)
(here $friends
have no id ) 这是您收到错误的
->where('user_id', $friends->id)
(这里$friends
没有id)
so first we take out all the ids of friends, and then take the posts which are made by the 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.