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

但是,这可能会打破口才,因为你的模式是不是代表你的数据库模型的了;它现在是两个独立模型的弗兰肯模型。