我有一个 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/