扩展 Laravel ORM
添加了按月分表的支持
$ composer require luffluo/laravel-orm-support:~1.0 -vvv
复制 Illuminate\Database\Query\Builder
类到根目录下 replaces\Database\Query\Builder.php
然后用下面的 getBindings
方法覆盖原来的
<?php
declare(strict_types = 1);
namespace Illuminate\Database\Query;
class Builder
{
/**
* Get the current query value bindings in a flattened array.
*
* @return array
*/
public function getBindings()
{
$bindings = Arr::flatten($this->bindings);
if ($this->unions && count($this->bindings['union']) <= 0) {
foreach ($this->unions as $union) {
$bindings = array_merge($bindings, $union['query']->getBindings());
}
}
return $bindings;
}
}
并在 composer.json
里添加如下配置, 然后执行 composer dump
{
"autoload": {
"files": [
"replaces/Database/Query/Builder.php",
]
}
}
表名要使用如下格式 xxxx_202111, xxxx_202112 等
use \Luffluo\LaravelOrmSupport\Traits\MonthlyScale;
class Model
{
use MonthlyScale;
}
添加上面的 Trait
到 model
后,就像原来使用 model
一样,会查询当月的数据
Model::query()->count();
// 上周
Model::queryForLastWeek()->count();
// 上上周
Model::queryForLastWeeks(2)->count();
Model::queryForPeriod('2019-01', '2019-11')->count();
Model::queryForYearMonth('201901')->count();
Model::queryForPeriod('2019-11-26', '2020-11-26')
->unionSelect('xxx', 'xxx')
->unionSelectRaw('xxx', 'xxx')
->count();
Model::queryForPeriod('2019-11-26', '2020-11-26')
->unionWhere('xxx', 'xxx')
->unionOrWhere('xxx', 'xxx')
->unionWhereIn('xxx', ['xx', 'xx'])
->unionWhereBetween('xx', ['xxx', 'xxx'])
->count();
Model::queryForPeriod('2019-11-26', '2020-11-26')
->unionGroupBy('xxx', 'xxx')
->count();
MIT