获取指定的列,并且设置某些列的别名: swoole 4.5,easy_swoole 3.x public function getUserInfo($id) { $user = UserModel::field(['id as user_id', 'nickname', 'avatar', 'country_code', 'telephone', 'email', 'language', 'xxx',
获取指定的列,并且设置某些列的别名:
swoole 4.5,easy_swoole 3.x
{
$user = UserModel::field(['id as user_id', 'nickname', 'avatar', 'country_code', 'telephone', 'email', 'language', 'xxx', 'xx'])
->get($id);
return $user;
}
注意:field方法一定要在get之前调用,不然查询sql的时候还是会查出所有字段,然后再做的过滤。
下面几个方法可以放在BaseModel里面,写起程序来事半功倍.
/*** 存在就取出,不存在就新建
* @author Bruce 2020/9/22
* @param array $values [供额外新增的字段]
* @param array $attributes [要查询的字段]
*/
public static function firstOrCreate(array $attributes, array $values = [])
{
if ($data = self::create()->get($attributes)) {
return $data;
}
$id = self::create()->data($attributes + $values)->save();
return self::create()->get($id);
}
/**
* 存在就更新,不存在就创建
* @author Bruce 2020/9/22
* @param array $values [供更新的字段]
* @param array $attributes [要查询的字段]
* @return bool|int
*/
public static function updateOrCreate(array $attributes, array $values = [])
{
if ($data = self::create()->get($attributes)) {
$data->update($values);
return $data;
}
$id = self::create()->data($attributes + $values)->save();
return self::create()->get($id);
}
/**
* @param int $id
*/
public static function updateByWhere($where, $data = [])
{
return self::create()->where($where)->update($data);
}
public static function fetchOneColumn(array $where = [], array $fields = [], $scalar = false)
{
if (count($fields) === 1) {
if ($scalar) {
return self::create()->where($where)->scalar($fields[0]);
}
return self::create()->where($where)->column($fields[0]);
}
return self::create()->field($fields)->get($where);
}
public static function fetchAll(array $where = [], array $fields = [])
{
return self::create()->field($fields)->all($where);
}