I come from cakePHP where it is possible to have every get or list query to include a standard where "something = something" in the Model. Per function in the controller this can be ignored, but for all others this is used.
Now I am wondering how to do this in Laravel 5. I would like to add something like below code in the Model or in the Controller (but preferably in the Model):
public function __construct(Page $page) {
$page->where('is_active', 1);
}
So that when running any query on the pages table it will only give me active pages. Except when I manually add where('is_active', 0)
or something else to include all active and inactive pages.
Any help would be very appreciated
答案 0 :(得分:2)
您可以通过在模型上使用查询范围来实现您想要的大部分内容。
你在你的模特中放了这样的东西:
/**
* Scope a query to only include active users.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive($query)
{
return $query->where('active', 1);
}
然后当你想要使用它时,你会做这样的事情:
$users = App\User::active()->orderBy('created_at')->get();
它没有为所有查询设置默认值,但它可能是更好的长期解决方案。文档在这里:http://laravel.com/docs/5.1/eloquent#query-scopes