laravel 常见提升技巧

一、关于路由方法命名【资源管理resource】

使用 Laravel resource 方法定义用户资源路由,可以少写很多代码,且严格按照了 RESTful 架构对路由进行设计。

语法
Route::resource('users', 'UsersController');
第一个参数 users 为资源名称,
第二个参数 UsersController 为控制器名称,

resource 方法将遵从 RESTful 架构为用户资源生成以下路由:

Route::get('/users', 'UsersController@index')->name('users.index');
Route::get('/users/create', 'UsersController@create')->name('users.create');
Route::get('/users/{user}', 'UsersController@show')->name('users.show');
Route::post('/users', 'UsersController@store')->name('users.store');
Route::get('/users/{user}/edit', 'UsersController@edit')->name('users.edit');
Route::patch('/users/{user}', 'UsersController@update')->name('users.update');
Route::delete('/users/{user}', 'UsersController@destroy')->name('users.destroy');
Copy
生成的资源路由列表信息:

HTTP 请求 URL 动作 作用
GET /users UsersController@index 显示所有用户列表的页面
GET /users/{user} UsersController@show 显示用户个人信息的页面
GET /users/create UsersController@create 创建用户的页面
POST /users UsersController@store 创建用户
GET /users/{user}/edit UsersController@edit 编辑用户个人资料的页面
PATCH /users/{user} UsersController@update 更新用户
DELETE /users/{user} UsersController@destroy 删除用户
View Code

 

备注:路由名称以功能名称来命名,类也是以功能名称来命名,方法名称用基本操作名来命名即可,不用拼接功能名+操作名

 

二、模型关联

1、封装查询方法

<?php

namespace App\Dao;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use ReflectionClass;

abstract class BaseDao
{
    use HasFactory;

    protected $is_del  = false;
    public    $sort    = ["id", 'desc'];
    protected $keyword = [];

    public function __construct()
    {
        $reflectionClass = new ReflectionClass($this->getModel());
        $constants       = $reflectionClass->getConstants();
        if (isset($constants['IS_DEL'])) {
            $this->is_del = true;
        }
    }

    public function __call($name, $arguments)
    {
        if (method_exists($this->getModel(), $name)) {
            $this->getModel()->$name(...$arguments);
        } else {
            throw new \Exception("Method {$name} does not exist");
        }
    }

    public function __get($name)
    {
        $reflectionClass = new ReflectionClass($this->getModel());
        $properties      = $reflectionClass->getProperties();
        $properties_arr  = [];
        foreach ($properties as $property) {
            if ($property->getName() == $name) {
                $property->setAccessible(true);
                $properties_arr = $property->getValue($this->getModel());
            }
        }
        if (!empty($properties_arr)) {
            return $properties_arr;
        } else {
            return null;
        }
    }

    /**
     * 获取当前模型
     * @return mixed
     */
    abstract protected function setModel(): string;

    /**
     * @param $keyword
     * @return mixed
     */
    public function setKeyword($keyword)
    {
        if (!empty($keyword)) {
            $this->keyword = $keyword;
        }
        return $this;
    }

    /**
     * 获取模型
     */
    protected function getModel()
    {
        return app()->make($this->setModel());
    }

    /**
     * 对数据进行统计
     * @param array $where
     * @param string $field [统计的字段]
     * @return int [统计数]
     */
    public function count(array $where = [], string $field = "id"): int
    {
        $keyword = $this->keyword;
        return $this->buildQuery($where)
            ->where($where)
            ->when(!empty($this->keyword), function ($q) use ($keyword) {
                $q->where($keyword);
            })
            ->count($field);
    }

    public function sum(array $where = [], string $field = "id"): int
    {
        return $this->buildQuery($where)->where($where)->sum($field);
    }

    /**
     * 使用distinct进行复杂统计
     * @param array $where
     * @return int
     */
    public function distinctCount(array $where = []): int
    {
        return $this->buildQuery($where)->where($where)->get()->count();
    }

    /**
     * 获取单个字段值
     * @param array $where
     * @param string $field [需要获取的字段值]
     * @return mixed
     */
    public function getValue(array $where, string $field = "id")
    {
        return $this->buildQuery($where)->where($where)->value($field);
    }

    /**
     * 获取单只包含单个字段是数据集合
     * @param array $where
     * @param array $with
     * @param string $field
     * @return array
     */
    public function getPluck(array $where, array $with = [], string $field = "id"): array
    {
        $in     = $where['in'] ?? [];
        $not_in = $where['not_in'] ?? [];
        unset($where['in'], $where['not_in']);
        return $this->getModel()
            ->where($where)
            ->when(!empty($with), function ($q) use ($with) {
                $q->with($with);
            })
            ->when(!empty($in), function ($q) use ($in) {
                $q->whereIn($in['key'], $in['value']);
            })
            ->when(!empty($not_in), function ($q) use ($not_in) {
                $q->whereNotIn($not_in['key'], $not_in['value']);
            })
            ->pluck($field)
            ->toArray();
    }

    public function getFind(int $id, array $with = [], array $field = [])
    {
        return $this->getModel()->when(!empty($field), function ($q) use ($field) {
            $q->select($field);
        })
            ->when(!empty($with), function ($q) use ($with) {
                $q->with($with);
            })
            ->find($id);
    }

    /**
     * 获取单条数据集合
     * @param array $where
     * @param array $with
     * @param array $field
     * @return mixed
     */
    public function getByInfo(array $where, array $with = [], array $field = [])
    {
        return $this->getModel()
            ->where($where)
            ->when(!empty($field), function ($q) use ($field) {
                $q->select($field);
            })
            ->when(!empty($with), function ($q) use ($with) {
                $q->with($with);
            })
            ->first();
    }

    public function buildQuery(&$where)
    {
        $query = $this->getModel();
        if( $this->is_del ) {
            $query = $query->where('is_del',0);
        }
        foreach ($where as $key => $data) {
            if (is_int($key)) {
                continue;
            }
            switch ($key) {
                case "in":
                    foreach ($data as $val) {
                        $query = $query->whereIn($val['field'], $val['value']);
                    }
                    unset($where['in']);
                    break;
                case "not_in":
                    foreach ($data as $val) {
                        $query = $query->whereNotIn($val['field'], $val['value']);
                    }
                    unset($where['not_in']);
                    break;
                case "has":
                    foreach ($data as $val) {
                        if ($val['callback'] instanceof \Closure) {
                            $query = $query->whereHas($val['relation'], $val['callback']);
                        }
                    }
                    unset($where['has']);
                    break;
                case "between":
                    foreach ($data as $val) {
                        $query = $query->whereBetween($val['field'], $val['value']);
                    }
                    unset($where['between']);
                    break;
                case "raw":
                    $query = $query->whereRaw($where['raw']);
                    unset($where['raw']);
                    break;
                case "distinct":
                    $concatString = 'DISTINCT CONCAT(' . implode(', \'-\', ', array_map(function ($field) {
                            return '`' . $field . '`'; // 使用反引号包围字段名以确保正确性
                        }, $data)) . ') as aggregate';
                    $query        = $query->selectRaw($concatString); //对结果集进行去重
                    unset($where['distinct']);
                    break;
                case "doesnt_have" :
                    foreach ($data as $val) {
                        $query = $query->doesntHave($val);
                    }
                    unset($where['doesnt_have']);
                    break;
                case "or_in":
                    foreach ($data as $val) {
                        $query = $query->orWhereIn($val['field'], $val['value']);
                    }
                    unset($where['or_in']);
                    break;
            }
        }
        return $query;
    }

    /**
     * @param array $where
     * @param int $limit
     * @param array $with
     * @param array $field
     * @param array $sort
     * @return mixed
     */
    public function getNewList(array $where = [], int $limit = 0, array $with = [], array $field = ['*'], $sort = [])
    {
        if (empty($sort)) {
            $sort = $this->sort;
        }
        $keyword = $this->keyword;
        return $this->buildQuery($where)
            ->when(!empty($field), function ($q) use ($field) {
                $q->select($field);
            })
            ->when(!empty($keyword), function ($q) use ($keyword) {
                $q->where($keyword);
            })
            ->where($where)
            ->orderBy($sort[0], $sort[1])
            ->when(!empty($with), function ($q) use ($with) {
                $q->with($with);
            })
            ->when($limit > 0, function ($q) use ($limit) {
                return $q->paginate($limit)->toArray();
            }, function ($q) {
                return $q->get()->toArray();
            });
    }

    /**
     * 获取数据列表,根据limit判断时候应该返回分页数据
     * @param array $where
     * @param array $field
     * @param array $with
     * @param int $limit
     * @return mixed
     */
    public function getList(array $where = [], int $limit = 0, array $with = [], array $field = [], $raw = '', $sort = [])
    {
        if (empty($sort)) {
            $sort = $this->sort;
        }
        $tmp_where = [];
        $in        = $where['in'] ?? [];
        $or        = $where['or'] ?? [];
        $not_in    = $where['not_in'] ?? [];
        $or_in     = $where['or_in'] ?? [];
        unset($where['in'], $where['not_in'], $where['or'], $where['or_in']);
        if ($this->is_del) {
            $tmp_where['is_del'] = 0;
        }
        return $this->getModel()->where($where)
            ->when(!empty($field), function ($q) use ($field) {
                $q->select($field);
            })
            ->when(!empty($raw), function ($q) use ($raw) {
                $q->whereRaw($raw);
            })
            ->where($tmp_where)
            ->when(!empty($field), function ($q) use ($field) {
                $q->select($field);
            })
            ->orderBy($sort[0], $sort[1])
            ->when(!empty($with), function ($q) use ($with) {
                $q->with($with);
            })
            ->when(!empty($in), function ($q) use ($in) {
                $q->whereIn($in['key'], $in['value']);
            })
            ->when(!empty($or), function ($q) use ($or) {
                $q->orWhere($or);
            })
            ->when(!empty($or_in), function ($q) use ($or_in) {
                $q->orWhereIn($or_in['key'], $or_in['value']);
            })
            ->when(!empty($not_in), function ($q) use ($not_in) {
                $q->whereNotIn($not_in['key'], $not_in['value']);
            })
            ->when($limit > 0, function ($q) use ($limit) {
                return $q->paginate($limit)->toArray();
            }, function ($q) {
                return $q->get()->toArray();
            });
    }

    public function getListRaw(array $where = [], int $limit = 0, array $with = [], array $field = [], $raw = '', $raw_field, $raw_data)
    {
        $tmp_where = [];
        $in        = $where['in'] ?? [];
        $not_in    = $where['not_in'] ?? [];
        unset($where['in'], $where['not_in'], $where['not_in']);
        /*  if( $this->is_del ) {
              $tmp_where['is_del'] = 0;
          }*/
        return $this->getModel()->where($where)
            ->when(!empty($field), function ($q) use ($field) {
                $q->select($field);
            })
            ->when(!empty($raw), function ($q) use ($raw) {
                $q->whereRaw($raw);
            })
            ->when(!empty($raw_data), function ($q) use ($raw_field, $raw_data) {
                if (!empty($raw_data)) {
                    $q->whereRaw('FIND_IN_SET(?,"' . $raw_field . '")', $raw_data);
                }
            })
            ->where($tmp_where)
            ->when(!empty($field), function ($q) use ($field) {
                $q->select($field);
            })
            ->orderBy($this->sort[0], $this->sort[1])
            ->when(!empty($with), function ($q) use ($with) {
                $q->with($with);
            })
            ->when(!empty($in), function ($q) use ($in) {
                $q->whereIn($in['key'], $in['value']);
            })
            ->when(!empty($not_in), function ($q) use ($not_in) {
                $q->whereNotIn($not_in['key'], $not_in['value']);
            })
            ->when($limit > 0, function ($q) use ($limit) {
                return $q->paginate($limit)->toArray();
            }, function ($q) {
                return $q->get()->toArray();
            });
    }

    public function saveData(array $data)
    {
        return $this->getModel()->create($data);
    }

    public function insertData(array $data)
    {
        return $this->getModel()->insert($data);
    }

    public function saveAllData(array $data, $auto_time = true)
    {
        if ($auto_time) {
            foreach ($data as &$val) {
                $val['created_at'] = time();
                $val['updated_at'] = time();
            }
        }
        return $this->getModel()->insert($data);
    }

    /**
     * @param array $where
     * @param $data
     * @return mixed|bool
     */
    public function saveOrUpdate(array $where, $data)
    {
        if (empty($where)) {
            $data['created_at'] = time();
            return $this->getModel()->insertGetId($data);
        }
        $data['updated_at'] = time();
        return $this->getModel()->updateOrInsert($where, $data);
    }

    public function batchUpdate(array $where, array $data): int
    {
        return  $this->buildQuery($where)->where($where)->update($data);
    }

    public function batchInUpdate(string $key, array $where, array $data): int
    {
        return $this->getModel()->whereIn($key, $where)->update($data);
    }

    public function del(array $where)
    {
        if ($this->is_del) {
            return $this->getModel()->where($where)->update(['is_del' => 1]);
        } else {
            return $this->getModel()->where($where)->delete();
        }
    }

    public function groupSql($field, $where)
    {
        return $this->buildQuery($where)
            ->where($where)
            ->select($field, \DB::raw('count(*) as total'))
            ->groupBy($field)
            ->get()
            ->count();
    }
}
View Code

 

2、一对一

    public function warehouse()
    {
        return $this->belongsTo(Warehouse::class,"warehouse_id",'id');
    }

 

3、一对多

    public function device()
    {
        return $this->hasMany(WarehouseDevices::class, "bind_id", 'id');
    }

 

posted on 2024-11-20 11:10  shenzen_小白  阅读(111)  评论(0编辑  收藏  举报

导航