How do I delete rows in Yii2?

You can use this way

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

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

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

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

Tags:

Yii2