有了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)'));
多亏了lukasgeiter的回答,我萌生了为此创建一个类的想法,该类扩展了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;
}
}
我现在可以使用它来创建许多不同的查询,所有查询都具有相同的where条件。
获取特定页面的浏览次数:
$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)'));
您可以创建一个自定义类,将所有函数传递给DB
facade exept您的自定义查询。像这样:
<?php
namespace App'Utilities;
use DB;
class CustomDB
{
private $db;
private static $instance = null;
private $exitCalls;
private function __construct()
{
$this->exitCalls = ['get', 'find', 'pluck', 'first', 'value', 'chunk', 'chunkById', 'count', 'max', 'avg', 'exists', 'doesntExist'];
}
public function __call($name, $arguments)
{
$result = call_user_func_array([self::$instance->db, $name], $arguments);
if (in_array($name, $this->exitCalls)) {
return $result;
}
return self::$instance;
}
public static function table($string)
{
if (self::$instance == null) {
self::$instance = new CustomDB();
}
self::$instance->db = DB::table($string);
return self::$instance;
}
public function myCustomQuery()
{
self::$instance->db->where('name','=','frank');
return self::$instance;
}
}
现在你可以简单地调用:
CustomDB::table('users')->myCustomQuery()->get();