在使用laravel開發web系統的過程,需要在model處為該模型統一添加一個條件或者多個條件,研究了一個laravel的模型類,發現model中有個方法是構建查詢的,方法如下:
/** * Register the global scopes for this builder instance. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return \Illuminate\Database\Eloquent\Builder */ public function registerGlobalScopes($builder) { foreach ($this->getGlobalScopes() as $identifier => $scope) { $builder->withGlobalScope($identifier, $scope); } return $builder; }
我們只需要在model里面修改這個方法的實現就可以
例如User
class Users extends Model { protected $table = 'users'; protected $hidden = [ ] foreach ($this->getGlobalScopes() as $identifier => $scope) { $builder->withGlobalScope($identifier, $scope); } //這里就可以隨便添加統一的條件了 $builder->where('channel_id','=',1); return $builder; }