如何在laravel / php

时间:2018-01-23 20:18:57

标签: php laravel-5.4

我是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] ...

该集合在屏幕截图中显示为掷骰子。我怎样才能迭代并获得所有朋友的id的数组。 enter image description here

enter image description here

1 个答案:

答案 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();