简体   繁体   English

在laravel 5.4我怎么才能得到用户朋友的帖子?

[英]In laravel 5.4 how can i get only the users friends posts?

$user_id = auth::user()->id;
$user_friends = User::find($user_id)->friends;
$user_friends_id = $user_friends->pluck('id');
$posts = Post::where('user_id', $user_friends_id)->get();
return view('dashboard')->with('posts', $posts);

So far i've got the users friends id's in $user_friends_id and then matching them to the user id on the posts but its only getting the first friends posts and not the rest. 到目前为止,我已经在$ user_friends_id中找到了用户朋友ID,然后将它们与帖子上的用户ID相匹配,但它只获得了第一个朋友帖子,而不是其他帖子。 How can i change it to get all the friends posts and not just the first friends? 如何更改它以获取所有朋友的帖子而不仅仅是第一批朋友?

You don't need to execute an additional query with find() and then get all friends objects just to get their IDs. 您不需要使用find()执行其他查询,然后获取所有朋友对象以获取其ID。 It's a huge overhead. 这是一个巨大的开销。 Just do this: 这样做:

Post::whereIn('user_id', auth()->user()->friends()->pluck('id'))->get()

You can use whereIn : 你可以使用whereIn

$user_id = auth::user()->id;
$user_friends = User::find($user_id)->friends;
$user_friends_id = $user_friends->pluck('id');
$posts = Post::whereIN('user_id', $user_friends_id)->get();
return view('dashboard')->with('posts', $posts);

In one line: 在一行中:

$posts = Post::whereIn('user_id', auth()->user()->friends()->pluck('id'))->get();

You can use whereIn , for which you need an array of IDs. 您可以使用whereIn ,您需要一组ID。 The Pluck function gives you a collection of just a specific column (key), so you need to call toArray on it to have an array with the values instead of a collection. Pluck函数为您提供了一个特定列(键)的集合,因此您需要在其上调用toArray以使数组具有值而不是集合。 Further, you can eliminate the extra query with User::find since you are looking for the authenticated user and you already have queried that with Auth::user() . 此外,您可以使用User::find消除额外查询,因为您正在查找经过身份验证的用户,并且您已经使用Auth::user()查询了该查询。

So I would say you need the following: 所以我想说你需要以下内容:

$user_friends = Auth::user()->friends;
$user_friends_id = $user_friends->pluck('id')->toArray();
$posts = Post::whereIn('user_id', $user_friends_id)->get();
return view('dashboard')->with('posts', $posts);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM