优化代码

main
gzydong 2021-09-04 23:20:50 +08:00
parent d0697ac658
commit 6212d439c9
4 changed files with 132 additions and 47 deletions

View File

@ -36,7 +36,7 @@ class TestCommand extends HyperfCommand
{ {
$repository = di()->get(ExampleRepository::class); $repository = di()->get(ExampleRepository::class);
// $repository->case4(); $repository->where_case2();
//$api = config('juhe_api.ip'); //$api = config('juhe_api.ip');
//$options = []; //$options = [];
//$client = di()->get(ClientFactory::class)->create($options); //$client = di()->get(ClientFactory::class)->create($options);

View File

@ -71,18 +71,20 @@ abstract class BaseRepository
* *
* @param array $where 查询条件 * @param array $where 查询条件
* @param string[] $fields 查询字段 * @param string[] $fields 查询字段
* @param bool $is_array 是否返回数组格式 * @param array $limit limit 条件 [offset,limit]
* @return Collection|array * @return array
*/ */
final public function get(array $where = [], array $fields = ['*'], bool $is_array = false) final public function get(array $where = [], array $fields = ['*'], array $limit = []): array
{ {
$this->handleField($fields); $this->handleField($fields);
$data = $this->buildWhere($where)->get($fields); $model = $this->buildWhere($where);
$is_array && $data = $data->toArray(); if ($limit && count($limit) == 2) {
$model->offset($limit[0] ?? 0)->limit($limit[1] ?? 0);
}
return $data; return $model->get($fields)->toArray();
} }
/** /**
@ -147,7 +149,7 @@ abstract class BaseRepository
} }
/** /**
* 删除数据 * 根据条件批量删除数据
* *
* @param array $where 删除的条件 * @param array $where 删除的条件
* @return int * @return int
@ -171,8 +173,8 @@ abstract class BaseRepository
/** /**
* 原生 SQL 查询 * 原生 SQL 查询
* *
* @param string $query * @param string $query 查询 SQL
* @param array $bindings * @param array $bindings 绑定数据
* @param bool $useReadPdo * @param bool $useReadPdo
* @return array * @return array
*/ */
@ -203,9 +205,7 @@ abstract class BaseRepository
] ]
]; ];
if ($total > 0) { if ($total > 0) $data['rows'] = $model->forPage($page, $size)->get($fields)->toArray();
$data['rows'] = $model->forPage($page, $size)->get($fields)->toArray();
}
return $data; return $data;
} }

View File

@ -23,10 +23,12 @@ class ExampleRepository extends BaseRepository
// 自增自减案例 increment decrement // 自增自减案例 increment decrement
public function case1() public function case1()
{ {
// 数据自增
// $this->increment(['id' => 1017], 'is_robot', 4, [ // $this->increment(['id' => 1017], 'is_robot', 4, [
// 'updated_at' => date('Y-m-d H:i:s') // 'updated_at' => date('Y-m-d H:i:s')
// ]); // ]);
// 数据自减
// $this->decrement(['id:gt' => 1017], 'is_robot', 1, [ // $this->decrement(['id:gt' => 1017], 'is_robot', 1, [
// 'updated_at' => date('Y-m-d H:i:s') // 'updated_at' => date('Y-m-d H:i:s')
// ]); // ]);
@ -35,25 +37,20 @@ class ExampleRepository extends BaseRepository
// 聚合查询相关案例 count, max, min, avg, sum // 聚合查询相关案例 count, max, min, avg, sum
public function case2() public function case2()
{ {
// $this->count([ // 统计总数
// 'id:gt' => 3000 // $this->count(['id:gt' => 3000]);
// ]);
// $this->max([ // 最大值
// 'id:gt' => 3000 // $this->max(['id:gt' => 3000], 'id');
// ], 'id');
// $this->min([ // 最小值
// 'id:gt' => 3000 // $this->min(['id:gt' => 3000], 'id');
// ], 'id');
// $this->avg([ // 平均值
// 'id:gt' => 3000 // $this->avg(['id:gt' => 3000], 'id');
// ], 'id');
// $this->sum([ // 求和
// 'id:gt' => 3000 // $this->sum(['id:gt' => 3000], 'id');
// ], 'id');
} }
// model value pluck exists doesntExist // model value pluck exists doesntExist
@ -132,7 +129,6 @@ class ExampleRepository extends BaseRepository
// 根据主键ID查询数据 // 根据主键ID查询数据
// $this->find(2054, ['id', 'mobile']); // $this->find(2054, ['id', 'mobile']);
// 主键查询没有就抛出错误 // 主键查询没有就抛出错误
// $this->findOrFail(20540000, ['id', 'mobile']); // $this->findOrFail(20540000, ['id', 'mobile']);
@ -176,7 +172,7 @@ class ExampleRepository extends BaseRepository
// $this->get([ // $this->get([
// 'id' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], // 'id' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
// 'gender' => 2 // 'gender' => 2
// ], ['id', 'mobile'],true); // ], ['id', 'mobile'],[0,10]);
// 分页获取数据 // 分页获取数据
// $data = $this->paginate([ // $data = $this->paginate([
@ -211,7 +207,9 @@ class ExampleRepository extends BaseRepository
public function other() public function other()
{ {
$model = $this->getModel(); // 获取 Model 实例
$model = $this->buildWhere();
} }
// where 条件查询案例 // where 条件查询案例
@ -229,19 +227,84 @@ class ExampleRepository extends BaseRepository
// in 或者 not in 查询 // in 或者 not in 查询
'id:in' => [1, 2, 3], 'id:in' => [1, 2, 3],
'id' => [1, 2, 3],
'id:not in' => [5, 6, 7], 'id:not in' => [5, 6, 7],
'id:gt' => 10, 'id:gt' => 10,
'id:lt' => 100, 'id:lt' => 100,
'mobile:like' => "138%",
'mobile:not like' => "1381%",
// or 查询(可嵌套使用)
'or' => [ 'or' => [
'field' => '', 'field' => '',
['field', '>', ''], ['field', '>', ''],
], 'or' => [
[
'field' => '',
['field', '>', ''], ['field', '>', ''],
],
['field', '>', ''],
],
// 排序
'order by' => [
'created_at' => 'desc',
'updated_at' => 'asc',
'`updated_at - created_at`' => 'desc'
],
// 分组
'group by' => [
'gender', 'is_robot',
],
'having by' => [
['account_id', '>', 100],
],
// 关联查询
'join table' => [
// orm 自带条件
// [$table, $first, $operator = null, $second = null, $type = 'inner']
// 数组方式
[
'users_emoticon', 'users_emoticon.user_id', '=', 'users.id', 'left'
],
// 闭包方法
['users_emoticon', function ($join) {
$join->on('users.id', '=', 'users_emoticon.user_id');
}, null, null, 'left']
] ]
]; ];
echo $this->buildWhere($where)->toSql();
}
public function where_case2()
{
$rows = $this->get([
'id:gt' => 2000,
], ['*'], [0, 2]);
var_dump($rows);
return;
$this->get([
'id:gt' => 3000,
'id:lt' => 4000,
'id:between' => [3000, 4000],
'or' => [
['mobile', 'like', '138%'],
['mobile', 'like', '139%'],
[
['id', '=', 12],
['id', '=', 13],
'or' => [
['id', '=', 12],
['id', '=', 13],
]
]
],
'is_robot' => 1,
]);
// select * from `lar_users` where `id` > '3000' and `id` < '4000' and `id` between '3000' and '4000' and (`mobile` like '138%' or `mobile` like '139%' or (`id` = '12' and `id` = '13')) and `is_robot` = '1'
} }
} }

View File

@ -153,11 +153,11 @@ trait RepositoryTrait
} }
/** /**
* 获取新的查询构造器 * 获取新的 Model 查询构造器
* *
* @return Builder * @return Builder
*/ */
protected function getQuery(): Builder protected function getBuilder(): Builder
{ {
return $this->model->newQuery(); return $this->model->newQuery();
} }
@ -170,7 +170,12 @@ trait RepositoryTrait
*/ */
final public function buildWhere(array $where = []): Builder final public function buildWhere(array $where = []): Builder
{ {
$model = $this->getQuery(); $model = $this->getBuilder();
// Join 关联处理
if ($joins = Arr::pull($where, 'join table')) {
$this->addJoinTable($model, (array)$joins);
}
// 处理排序数据 // 处理排序数据
if ($order = Arr::pull($where, 'order by')) { if ($order = Arr::pull($where, 'order by')) {
@ -189,6 +194,10 @@ trait RepositoryTrait
// 判断是否存在查询条件 // 判断是否存在查询条件
if (!empty($where)) { if (!empty($where)) {
if (count($where) === 1 && isset($where['or'])) {
$where = $where['or'];
}
$this->bindWhere($model, $where); $this->bindWhere($model, $where);
} }
@ -242,6 +251,19 @@ trait RepositoryTrait
}); });
} }
/**
* Join 关联查询
*
* @param \Hyperf\Database\Model\Builder $model
* @param array $joins
*/
private function addJoinTable(Builder $model, array $joins)
{
foreach ($joins as $join) {
$model->join(...$join);
}
}
/** /**
* 添加排序信息 * 添加排序信息
* *