yii 框架 afterSave Model 数据变更 同步数据 处理新增了逻辑

发布时间 2023-07-14 17:48:26作者: 磊有三颗小石头

/**
* 来源
* 1.Model::updateAll()
* 2.Model::findOne(id)->save()
* @param $attributes
* @param $condition
* @param $params
* @return int
* @throws \yii\db\Exception
*/
public static function updateAll($attributes, $condition = '', $params = [])
{
//这里需要提前抛出,如果执行后抛出,同样的条件可能查不到对应的数据,导致更新失败
(new self())->afterSave(false, array_merge(['where' => $condition], $attributes));

$command = static::getDb()->createCommand();

$command->update(static::tableName(), $attributes, $condition, $params);
return $command->execute();
}

public function afterSave($insert, $changedAttributes) {
parent::afterSave($insert, $changedAttributes);

if ($insert) {
$primaryKey = $this->getPrimaryKey();
$data = $this->isOneUserOrder($primaryKey);
if($data){
$this->addData($data);
}
}

if(isset($changedAttributes['where']) && isset($changedAttributes['opnop_visible'])){

if($changedAttributes['opnop_visible'] == 1){

if(isset($changedAttributes['where']['opnop_id'])){

$opnop_id = $changedAttributes['where']['opnop_id'];

$opn_operator = OpnOperator::find()->select('opn_id,user_id,username')->where(['opnop_id'=>$opnop_id])->asArray()->one();

$opn_id = $opn_operator['opn_id'];
$oper = TmsOperationFee::find()->where(['opn_id'=>$opn_id])->one();

if($opn_operator && $oper){
$oper->user_id = $opn_operator['user_id']?:0;
$oper->username = $opn_operator['username']?:'';
$oper->save();
}
}

}
}
}