Yii deleteAll() records with condition

13,095

Solution 1

Seems you call the function delete() in wrong way ... try passing value this way

VerificationCode::model()->deleteAll('user_id = :user_id', array(':user_id' => $user->id));

Solution 2

If you want to delete record with specified attributes, the cleanest way for this is to use deleteAllByAttributes():

VerificationCode::model()->deleteAllByAttributes(['user_id' => $user->id]);
Share:
13,095
grhmstwrt
Author by

grhmstwrt

Updated on June 05, 2022

Comments

  • grhmstwrt
    grhmstwrt almost 2 years

    I've set up a log in process where a verification code is generated, and when successful, is then removed. However, i want to make sure that if there's multiple verification codes for the same user, upon log in success, delete all records for that user.

    Here's my code

    if ($model->validate() && $model->login()) {
    
        //delete this verification code
        $verificationCode->delete();
        //delete all existing codes for user_id
        VerificationCode::model()->deleteAll('user_id',$user->id);
    
        Yii::app()->user->setReturnUrl(array('/system/admin/'));
    
        $this->redirect(Yii::app()->user->returnUrl);
    }
    

    However, this seems to just delete all the records, regardless on different user_id's in table. Can anyone see where I'm going wrong?

  • grhmstwrt
    grhmstwrt almost 8 years
    Thanks, this code is giving me a syntax error and i can't see what is should be?
  • grhmstwrt
    grhmstwrt almost 8 years
    Still getting a syntax error, can this condition=>Paramus method be called from a controller?
  • grhmstwrt
    grhmstwrt almost 8 years
    Thanks for your help scaisEdge - answer was correct, but syntax was wrong, had to read up on the documentation, deleteAll() params must be passed as an array, like so VerificationCode::model()->deleteAll('user_id = :user_id', array(':user_id' => $user->id));
  • Harry B
    Harry B over 4 years
    This isn't correct. It either needs to be deleteAll($condition, $params) or deleteAll($Criteria)
  • ScaisEdge
    ScaisEdge over 4 years
    @HarryB the right suggestion was already in comment anyway answer updated.. thanks ..