Files
code-bang/backend/application/common/traits/ServiceTrait.php
T
2026-09-17 16:25:31 +08:00

86 lines
2.1 KiB
PHP

<?php
namespace app\common\traits;
use app\common\service\CommonService;
trait ServiceTrait
{
public static $instance;
/** @var CommonService */
public static $Common = CommonService::class;
/**
* 单例获取当前服务
* @return static
*/
public static function instance()
{
if (is_null(static::$instance)) {
static::$instance = new static();
}
return static::$instance;
}
/**
* 获取单条数据
* @param $where
* @param string|array $with
* @param string|array $order
* @return mixed
*/
public static function getOne($where, $with = [], $order = [], $params = [])
{
$model = self::$Model::with($with)->where($where);
if ($order) {
$model->order($order[0] ?? 'id', $order[1] ?? 'asc');
}
if (!empty($params['withCount'])) {
$model->withCount($params['withCount']);
}
return $model->find();
}
/**
* 获取列表数据
* @param $where
* @param int $page_size
* @param string|array $order --'id desc,status'|['order','id'=>'desc']
* @param string $group
* @param string|array $with
* @param array $params
* @return mixed
*/
public static function getList($where, $page_size = 0, $order = [], $group = '', $with = [], $params = [])
{
$model = self::$Model::where($where);
if ($order) {
$model->order($order);
}
if ($group) {
$model->group($group);
}
if ($with) {
$model->with($with);
}
if (!empty($params['withCount'])) {
$model->withCount($params['withCount']);
}
$res = $page_size ? $model->paginate($page_size, false, $params['config'] ?? []) : $model->select();
return $res;
}
/**
* 调用模型静态方法
* @param $funName
* @param $args
* @return mixed
*/
public static function __callStatic($funName, $args)
{
$res = self::$Model::$funName(...$args);
return $res;
}
}