public function save($data = [], $where = [], $sequence = null)
{
if (!empty($data)) {
// 数据自动验证
if (!$this->validateData($data)) {
return false;
}
// 数据对象赋值
foreach ($data as $key => $value) {
$this->setAttr($key, $value, $data);
}
if (!empty($where)) {
$this->isUpdate = true;
}
}
// 检测字段
if (!empty($this->field)) {
foreach ($this->data as $key => $val) {
if (!in_array($key, $this->field)) {
unset($this->data[$key]);
}
}
}
// 数据自动完成
$this->autoCompleteData($this->auto);
// 自动写入更新时间
if ($this->autoWriteTimestamp && $this->updateTime) {
$this->setAttr($this->updateTime, null);
}
// 事件回调
if (false === $this->trigger('before_write', $this)) {
return false;
}
if ($this->isUpdate) {
// 自动更新
$this->autoCompleteData($this->update);
// 事件回调
if (false === $this->trigger('before_update', $this)) {
return false;
}
// 去除没有更新的字段
$data = [];
foreach ($this->data as $key => $val) {
if (in_array($key, $this->change) || $this->isPk($key)) {
$data[$key] = $val;
}
}
if (!empty($this->readonly)) {
// 只读字段不允许更新
foreach ($this->readonly as $key => $field) {
if (isset($data[$field])) {
unset($data[$field]);
}
}
}
if (empty($where) && !empty($this->updateWhere)) {
$where = $this->updateWhere;
}
$pk = $this->getPk();
if (is_string($pk) && isset($data[$pk])) {
if (!isset($where[$pk])) {
unset($where);
$where[$pk] = $data[$pk];
}
unset($data[$pk]);
}
$result = $this->db()->where($where)->update($data);
// 清空change
$this->change = [];
// 更新回调
$this->trigger('after_update', $this);
} else {
// 自动写入
$this->autoCompleteData($this->insert);
// 自动写入创建时间
if ($this->autoWriteTimestamp && $this->createTime) {
$this->setAttr($this->createTime, null);
}
if (false === $this->trigger('before_insert', $this)) {
return false;
}
$result = $this->db()->insert($this->data);
// 获取自动增长主键
if ($result) {
$insertId = $this->db()->getLastInsID($sequence);
$pk = $this->getPk();
if (is_string($pk) && $insertId) {
$this->data[$pk] = $insertId;
}
}
// 标记为更新
$this->isUpdate = true;
// 清空change
$this->change = [];
// 新增回调
$this->trigger('after_insert', $this);
}
// 写入回调
$this->trigger('after_write', $this);
return $result;
}