php - Laravel 在 hasManyThrough 中包含用户的帖子

标签 php mysql laravel laravel-5

我正在创建一个社交媒体应用程序,其中用户的提要通过 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/

相关文章:

php - 如何使用php变量在javascript中循环

mysql - 为什么 MYSQL AND 运算符在尝试提取同一列中的数据时不起作用?

mysql - 我的查询有效,但我正在努力通过合并另一个表来扩展它

php - 如何在 PHP 中自动绑定(bind)实现?

php - 从/但包含 .. 开始的路径仍然是绝对路径吗?

php - 嵌套排序(toHierarchy)将结果存储在MySQL中

mysql - 在选择中的计算中使用连接计数

php - 用laravel迁移一张表,错误 "MySQL server has gone away"和 "Packets out of order"

拉拉维尔。在具有关系的模型中使用scope()

javascript - 获取一个字符串并仅插入该字符串中的数字