Alireza
Alireza

Reputation: 6848

How to update a record based on another table's column value in Yii

I have 2 tables. One for profiles and one for users. What I'm trying to achieve is to update a field in profiles table, based on a condition in users table.

I want to finally achieve to the following query:

UPDATE profile
   SET p.cost = 1200
FROM Profile p 
   INNER JOIN users u ON p.user_id = u.id
WHERE u.status = 1

Upvotes: 0

Views: 182

Answers (2)

Jeroen
Jeroen

Reputation: 567

In the 'afterSave' function of a model you could check the condition ($user->hasProfile) http://www.yiiframework.com/doc/api/1.1/CActiveRecord#onAfterSave-detail and then simply update the profile. Example:

public function afterSave() {
    if($this->status == 1) {
        $this->profile->cost = 1200;
        $this->profile->save();
    }
}

Upvotes: 0

Rohit Suthar
Rohit Suthar

Reputation: 3628

Simply you can use TRIGGERS in your SQL or MYSQL. so you can do all actions on another or related tables like - INSERT, UPDATE & DELETE.

eg. - http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx

Upvotes: 1

Related Questions