Reputation: 966
So my goal is update table column which sum of another table column
This is my beforeSave method in the first model (Consumption)
:
public function beforeSave($insert){
Accounts::updateAccount($this->user_id);
return parent::beforeSave($insert);
}
And In the Accounts model Accounts model updateAccount function:
public static function updateAccount($user_id){
$account=self::find()->where(["user_id"=>$user_id])->one();
if(!$account){
$account=new Accounts();
$account->user_id=$user_id;
$account->default_currency=Currency::getDefault()->id;
$account->value=0;
$account->code=Accounts::getAutoCode();
$account->created=time();
$account->status=1;
$account->save();
}
$sum=Consumption::find()->where(["user_id"=>$user_id])->sum("value");
$account->value=$sum;
$account->save();
}
This function if condition works(id account not yet, it create new one for this user). But after $account->value=$sum; $account->save();
doesn't save, any errors.
My validation rule for Accounts model:
public function rules()
{
return [
[['user_id', 'default_currency', 'value', 'status','code'], 'required'],
[['created', 'user_id', 'default_currency', 'status',], 'integer'],
];
}
Upvotes: 2
Views: 397
Reputation: 133360
Could be an Account validation problem try with
$sum=Consumption::find()->where(["user_id"=>$user_id])->sum("value");
$account->value=$sum;
$account->save(false);
if with the param set to false the account si saved then check selectively your Account validation rules and provide to review the rules or the application logic properly
Upvotes: 1