Model示例
class UserModel extends Model
{protected $table = 'tb_user';protected $casts = ['alias' => 'array'];
}
直接存alias
字段,数据库会显示unicode码
["\u80c3\u75db\u554a"]
class UserModel extends Model
{public function setAliasAttribute($option){$this->attributes['alias'] = json_encode($option, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);}
}
class UserModel extends Model
{protected $table = 'tb_user';protected $casts = ['alias' => 'array'];// 覆盖asJson方法protected function asJson($value){return json_encode($value, JSON_UNESCAPED_UNICODE);}
}
trait UnicodeJsonTrait
{/*** 序列化json* @param $value* @return false|string*/protected function asJson($value){return json_encode($value, JSON_UNESCAPED_UNICODE);}
}
直接在基类里使用(也可以在基类中覆写)
class BaseModel extends Model
{use UnicodeJsonTrait;
}
继承基类
class UserModel extends BaseModel
{protected $table = 'tb_user';protected $casts = ['alias' => 'array'];
}
public function get($model, string $key, $value, array $attributes){return json_decode($value, true);}public function set($model, string $key, $value, array $attributes){return json_encode($value, JSON_UNESCAPED_UNICODE);}
}
使用
protected $table = 'tb_user';protected $casts = ['alias' => JsonCast::class,];
}
save/create可以正常触发数据转换,update的时候需要注意
平常更新数据是这样的
$this->where(xxx)->update(xxx)
需要注意的是,这样写不会触发updating和updated事件
需要先获取模型再进行对应的操作,才能触发对应的模型事件
$this->where(xxx)->first()->update(xxx)// 或
$this->find(xxx)->update(xxx)
上一篇:微信小程序路由
下一篇:一个例子了解operator+