使用 Eloquent 模型添加范围很容易:
public function scopeMyScope($query)
{
// Do stuff to that $query
}
但如何添加范围DB::table
?
我使用此查询来获取页面浏览量:
$views = DB::table('page_views')
->where('id', $this->id)
->where('agent', 'NOT LIKE', '%bot%')
->count(DB::raw('distinct session, DATE(created_at)'));
我还通过其他查询显示最受欢迎的页面等,但具有相同的where
状况。所以我只想定义我的where
条件一次并在所有其他页面视图中重复使用它们DB::table
查询。
DB::table
不支持范围。您可以做的只是编写一个小函数,该函数对查询执行一些操作并返回它。语法不是那么好,但它可以工作:
function applyScope($query){
$query->whereNotNull('deleted_at');
$query->where('foo', 'bar');
return $query;
}
进而:
$query = DB::table('page_views')
->where('id', $this->id)
->where('agent', 'NOT LIKE', '%bot%');
$query = applyScope($query);
$views = $query->count(DB::raw('distinct session, DATE(created_at)'));
或者更短的语法:
$views = applyScope( DB::table('page_views')
->where('id', $this->id)
->where('agent', 'NOT LIKE', '%bot%')
)->count(DB::raw('distinct session, DATE(created_at)'));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)