讨论数量:
简单的看应该是全局作用域Global Scope
的能力:用过滤关系的中间表作为条件,作用域里面写上这个筛选条件,既可以做到过滤。
Schema::create('block_users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->comment('用户ID');
$table->unsignedBigInteger('block_user_id')->comment('屏蔽用户ID');
$table->timestamps();
});
屏蔽帖子的话定义到这个模型屏蔽用户的关系
public function blockUsers():BelongsTo
{
return $this->belongsTo(BlockUser::class,'user_id', 'block_user_id');
}
定义好全局作用域
class BlockUserRelationScope implements Scope
{
protected $userId;
public function __construct(int $userId)
{
$this->userId = $userId;
}
public function apply(Builder $builder, Model $model)
{
$builder
->when(!empty($userId), function (Builder $builder) {
$builder->whereDoesntHave('blockUsers', function (Builder $builder) {
$builder->where('user_id', $this->userId);
});
});
}
}
然后在普通用户访问的中间件或控制器里面应用这个作用域
Post::addGlobalScope(new BlockUserRelationScope(auth()->id()));
推荐文章: