laravel為模型中所有查詢統一添加WHERE條件


    在使用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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM