Socket/freedom/traits/ModelTrait.php
2026-01-28 23:48:20 +08:00

94 lines
2.2 KiB
PHP

<?php
namespace freedom\traits;
trait ModelTrait{
/**
* 获取单条数据
* @param array|int $where
* @return array
*/
public static function get($where): array
{
if (!is_array($where)) {
$find = self::find($where);
} else {
$find = self::where($where)->find();
}
if ($find) return $find->toArray();
else return [];
}
/**
* 获取某个字段值
* @param int $where
* @param
* @return string|int|double
*/
public static function getFieldValue($where,$field): string
{
$value = self::where($where)->value($field);
if ($value) return $value;
else return '';
}
/**
* 添加多条数据
* @param $group
* @param bool $replace
* @return int
*/
public static function setAll($group, bool $replace = false): int
{
return self::insertAll($group, $replace);
}
/**
* 修改一条数据
* @param $data
* @param $id
* @param $field
* @return bool $type 返回成功失败
*/
public static function edit($data, $id, $field = null): bool
{
$model = new self;
if (!$field) $field = $model->getPk();
$res = $model->update($data, [$field => $id]);
if (isset($res->result))
return 0 < $res->result;
else if (isset($res['data']['result']))
return 0 < $res['data']['result'];
else
return false != $res;
}
/**
* 查询一条数据是否存在
* @param $map
* @param string $field
* @return bool 是否存在
*/
public static function be($map, string $field = ''): bool
{
$model = (new self);
if (!is_array($map) && empty($field)) $field = $model->getPk();
$map = !is_array($map) ? [$field => $map] : $map;
return 0 < $model->where($map)->count();
}
/**
* 删除一条数据
* @param $id
* @return bool $type 返回成功失败
*/
public static function del($id): bool
{
return false !== self::destroy($id);
}
}