mysql - Laravel:仅向订阅者加载具有隐私的帖子

标签 mysql laravel model-view-controller

我有一个 View ,其中加载并显示数据库中的帖子。每个帖子都有可由用户设置的隐私。如果隐私为 1,则任何人都可以查看该帖子。如果隐私为2,则该帖子只能由订阅该用户的用户查看。

如何才能仅向订阅者而不向任何人显示具有隐私 2 的帖子?

UserModel 上的帮助程序类

public function isFollowed()
{
    return $this->followers()
        ->where('follower_id', auth()->id())
        ->where('followers.active', 1)
        ->exists();
}

加载帖子

$posts = Post::with('comments', 'tags')->whereIn('posts.privacy', [1, 2])->where('posts.status', 1)->where('posts.archived', 0)->where('posts.type', '!=', 7)->latest()->paginate(15);

最佳答案

您只需在限制范围内进行区分即可。因为您还有一些其他约束,所以有必要将 OR 连接约束放在它们自己的 where() 中:

use Illuminate\Database\Eloquent\Builder;

$posts = Post::query()
    ->with('comments', 'tags')
    ->where('posts.status', 1)
    ->where('posts.archived', 0)
    ->where('posts.type', '!=', 7)
    ->where(function (Builder $query) {
        $query>where('posts.privacy', 1)
            ->orWhere(function (Builder $query) {
                $query->where('posts.privacy', 2)
                    ->whereExists(function ($query) {
                        $query->select(DB::raw(1))
                            ->from('followers')
                            ->whereColumn('followers.user_id', 'posts.user_id')
                            ->where('followers.follower_id', auth()->id())
                            ->where('followers.active', 1);
                    });
            });
    })
    ->latest()
    ->paginate(15);

我不太确定 followers 表中除了 follower_id 之外的第二列是什么,所以我假设 user_id。这很可能需要改变。

顺便说一句,您所描述的听起来更像是可见性,而不是隐私。如果我可以订阅你(不受限制和接受你的内容)并且我突然看到你的更多内容,这几乎不是隐私。

关于mysql - Laravel:仅向订阅者加载具有隐私的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57535886/

相关文章:

javascript - Nodejs,最好有很多相同的要求或使用句柄?

php - 什么时候应该实例化 Controller ?

MySQL键值表一次更新多个ID的多行

mysql - 请告诉我mysql查询

javascript - 如果循环获取数据,如果存在于表中,如果不存在,则在表和 javascript 中插入值以获取有关写入配置文件 ID 的数据

laravel - 如何在 json 响应中使 laravel 护照身份验证重定向?

php - 如何在laravel中获取mysql COUNT查询值

php - 如何使用 RedBeanPHP 管理 MySQL 表的多对多连接

php - 在 Laravel 5.4 中安装 Laracast Generator 后出现 Trait 'Illuminate\Console\AppNamespaceDetectorTrait' not found 错误

ios - 我的模型对象是否应该负责下载它们自己的资源?