laravel sava 保存数据 遇到问题
①数据库是分表的 按日期分表 比如:day_01,day_02....
②在更新数据时 先按条件查询出day_01表里面的一条数据 为:
$objData = $objModel->setTable("day_01")->where(['user_id'=>123])->first();
③在更新数据时
//下面只是举例:setTable 不管是day_01 还是day_02都会返回1(这里特意set一个错的表 前提是day_02表没有user_id=123的数据)
$intNum = $objData->num;
②$objData->setTable("day_02");$objData->num = $intNum+20; $isRs = $objData->save();
dd($isRs);//总返回1
④$isRs这时候这个返回 1 按道理应该是0 使用监听器监听sql 打印执行的sql也是错的 为什么会返回1
经过几天的研究
监听的sql
select * from day_01 where user_id=123;//执行成功
update day_02 set num=30 where user_id=123;//执行失败
在源码
vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php
第606行(laravel5.5) performUpdate()
628行 $this->setKeysForSaveQuery($query)->update($dirty);
这里其实返回0 但laravel没有去判断 其返回值 直接在方法下面返回true了
#源码
protected function performUpdate(Builder $query)
{
// If the updating event returns false, we will cancel the update operation so
// developers can hook Validation systems into their models and cancel this
// operation if the model does not pass validation. Otherwise, we update.
if ($this->fireModelEvent('updating') === false) {
return false;
}
// First we need to create a fresh query instance and touch the creation and
// update timestamp on the model which are maintained by us for developer
// convenience. Then we will just continue saving the model instances.
if ($this->usesTimestamps()) {
$this->updateTimestamps();
}
// Once we have run the update operation, we will fire the "updated" event for
// this model instance. This will allow developers to hook into these after
// models are updated, giving them a chance to do any special processing.
$dirty = $this->getDirty();
if (count($dirty) > 0) {
$this->setKeysForSaveQuery($query)->update($dirty);
$this->fireModelEvent('updated', false);
$this->syncChanges();
}
return true;
}
你更新数据的时候,重新实例化一个模型,起名叫$objDataNew再试试