我正在创建一个社交媒体应用程序,其中用户的提要通过 hasManyThrough
生成。对经过身份验证的用户运行函数,如下所示:Auth::user()->feed
。调用的函数如下所示:
public function feed() {
$posts = $this->hasManyThrough(
'App\Post',
'App\Follow',
'follow_by',
'user_id',
'id',
'target_id'
)->with('user', 'likes', 'comments')
->orderBy('id', 'DESC');
return $posts;
}
这样做是因为我想检查经过身份验证的用户正在关注哪些用户,然后找到这些人的帖子。但是,我还想在查询中包含经过身份验证的用户的帖子。以前,我已经通过单独完成了此操作
$selfPosts = Post::where('user_id', Auth::user()->id)->with('user', 'likes', 'comments')->get();
然后使用 $posts = $selfPosts->merge($followPosts)->sortByDesc('id');
合并查询.
合并查询的问题有很多,例如我无法使用 limit 或 offset 。我的问题是,如何将经过身份验证的用户的帖子包含在 feed
中功能?
最佳答案
正如 Colin Barstow 在评论中建议的那样,一个简单的解决方案可能是解决此问题的最佳方案,而不是进行大量高级关系和合并。这是我的最终解决方案(感谢科林):
$DB_follows = Follow::where('follow_by', Auth::user()->id)->get();
$follows = [Auth::user()->id];
foreach ($DB_follows as $follow) {
array_push($follows, $follow->target_id);
}
$posts = Post::whereIn('user_id', $follows)->with('user', 'likes', 'comments')->orderBy('id', 'DESC')->get();
return $posts;
关于php - Laravel 在 hasManyThrough 中包含用户的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50429787/