简体   繁体   中英

how to combine 2 model requests into one query

I have 2 models for 2 tables

"sessions" table:

session_id | user_id | other fields

"usercash" table:

user_id | amount | other fields

these 2 tables dont have any kind of relations one to another.

i receive session_id and my goal is to get amount and update it. with the pure SQL can do amount selection easy with one simple query by joining tables by user_id.

it is possible to use models and criteria to generate one query so i can use userCashModel->save() to update amount?

at the moment im doing it this way with 2 queries to database :(

        $session_model = Sessions::model()->findByAttributes(array('session_id'=>$session_id));

        // updating the amount 
        $user_cash = Usercash::model()->findByAttributes(array('userId'=>$session_model->user_id));
        $user_cash->realMoney += (double)$amount;
        $user_cash->save();

In yii1 you could use a findBySql

 $user_cash = Usercash::model()->findBySql(
 " select * from usercash 
    innner join sessions on sessions.user_id = usercash.user_id 
    and sessions.session_id = :act_session_id", array(':act_session_id' => $session_id)
 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM