2016-09-16 6 views
1

新しいモデルを取得するたびにクエリビルダを変更するにはどうすればよいですか?毎回特定のモデルからクエリビルダを変更する - Laravel 5.3

私は以下のメソッドをオーバーライドすることが機能することを発見しましたが、これを行うのがうまくいきません。これを行うより良い方法はありますか?

だから、->join()を特定のモデルに対して毎回実行するようにします。

!!私はprotected $with = [];プロパティを使用したくないので、不要なときに余分なクエリを実行したくないためです。

public function newQueryWithoutScopes() 
{ 
    $builder = $this->newEloquentBuilder(
     $this->newBaseQueryBuilder() 
    ); 

    // Once we have the query builders, we will set the model instances so the 
    // builder can easily access any information it may need from the model 
    // while it is constructing and executing various queries against it. 
    return $builder->setModel($this)->join('join statement comes here')->with($this->with); 
} 
+3

ModelクラスブートメソッドでEloquntグローバルスコープを使用するhttps://laravel.com/docs/5.3/eloquent#global-scopes – TheFallen

答えて

1

モデルを使用するたびにクエリに影響を与えるには、newQueryメソッドを使用できます。

public function newQuery($excludeDeleted = true){ 
    return parent::newQuery()->join('orders', 'users.id', '=', 'orders.user_id'); 
} 

しかし、あなたのモデルがデータベースモデルをもはや代表していないので、これはおそらくEloquentを破ります。今は2つの別々のモデルのフランケンモデルです。

関連する問題