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?
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();