Bloodhound
Bloodhound

Reputation: 2966

How do I delete rows in Yii2?

I want to delete a row in database based on some condition. I tried like this

$fanclub        =   FanClub::find()->where(['user_id'=>$userid])->
            andwhere(['crew_member_id'=>$id])->one();
            if($fanclub)
            {
                $fanclub->delete();
            }

is this the right way to delete a row in database?

Upvotes: 17

Views: 64668

Answers (4)

Eslam Sameh Ahmed
Eslam Sameh Ahmed

Reputation: 4022

You can use this way

ProjectEmployee::deleteAll(['and',
            [ 'employee_id'=>$this->id],
            ['in', 'project_id', [2,5,7]]]
        );

But note that this can be used to delete single or multiple rows based on the array of in

Upvotes: 15

There you are getting record first, but you can do it directly

$fanclub = FanClub::find()
  ->where(['user_id'=>$userid])
  ->andwhere(['crew_member_id'=>$id])
  ->one()
  ->delete();

Upvotes: 3

Ramya Sri
Ramya Sri

Reputation: 25

$x = Yii::$app->db->createCommand("
    DELETE FROM group_members 
    WHERE group_id = '$id' 
    AND member_id = '$usr'
")->execute();

Upvotes: 1

arogachev
arogachev

Reputation: 33548

When working with models (ActiveRecord), yes, this is the right way.

You can use $model->delete() for deleting model. As the result, according row in related table will be deleted.

You can use beforeDelete() and afterDelete() event handlers together with this method to handle some tasks related with deletion.

Alternatives without using model:

\Yii::$app
    ->db
    ->createCommand()
    ->delete('users', ['id' => 1])
    ->execute();

or

use yii\db\Query;

...

(new Query)
    ->createCommand()
    ->delete('users', ['id' => 1])
    ->execute();

Upvotes: 30

Related Questions