Reputation: 2966
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
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
Reputation: 95
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
Reputation: 25
$x = Yii::$app->db->createCommand("
DELETE FROM group_members
WHERE group_id = '$id'
AND member_id = '$usr'
")->execute();
Upvotes: 1
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