使用雄辩的模型添加范围很容易:
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)'));
由于lukasgeiter answer,我有了一个为此创建一个类的想法,该类扩展了DB
并返回可以基于以下条件建立的查询的开头:
class PageViewQueryBuilder extends DB {
public static function table()
{
$query = parent::table('page_views')
->where('agent', 'NOT LIKE', '%bot%')
->where('agent', 'NOT LIKE', '%spider%')
->where('agent', 'NOT LIKE', '%crawler%')
;
return $query;
}
}
我现在可以使用它来创建许多不同的查询,所有查询的条件都相同。
获取特定页面的观看次数:
$count = PageViewQueryBuilder::table()
->where('page_id', $id)
->count(DB::raw('distinct session, DATE(created_at)'));
获取特定页面的所有视图:
$views = PageViewQueryBuilder::table()
->where('page_id', $id)
->orderBy('created_at', 'DESC')
->groupBy('session', DB::raw('DATE(created_at)'))
->get();
获取最近三个月最受欢迎的10个页面:
$views = PageViewQueryBuilder::table()
->selectRaw('page_id as page_id, count(distinct session, DATE(created_at)) as page_views')
->whereRaw('created_at BETWEEN NOW() - INTERVAL 3 MONTH AND NOW()')
->groupBy('page_id')
->orderBy('page_views', 'desc')
->limit(10)
->get();
[使用lukas的解决方案就像对待美食一样;我从定义了模型的模型中调用范围,只是避免了重复功能。
$query = DB::table('page_views')
->where('id', $this->id)
->where('agent', 'NOT LIKE', '%bot%');
$query = (new myModel())->scopeMyScope($query);
$views = $query->count(DB::raw('distinct session, DATE(created_at)'));