2016-09-16 29 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'); 
} 

但是,這可能會打破口才,因爲你的模式是不是代表你的數據庫模型的了;它現在是兩個獨立模型的弗蘭肯模型。