Yii2 Delete Query

Model delete()

$model = User::find($id);
$model->delete();

delete() With Condition

$connection	->createCommand()
			->delete('tbl_user', 'status = 0')
			->execute();

delete() With Query

$connection	->createCommand('DELETE FROM tbl_user WHERE userid=:userid')
			->execute();

delete() With Prepared Statements

Sample 1:

$model = $connection->createCommand('DELETE FROM tbl_user WHERE userid=:userid');
$model->bindParam(':userid', $userid);
$userid = 5;
$model->execute();

Sample 2:

Delete multiple users using prepared statements (in yii2).

$model = $connection->createCommand('DELETE FROM tbl_user WHERE userid=:userid');
$model->bindParam(':userid', $userid);
//delete user 1
$userid = 1;
$model->execute();
//delete user 2
$userid = 2;
$model->execute();

find() And Delete()

Sample1

$user = User::findOne(2);
$user->delete();
//Output Query
//DELETE FROM `tbl_user` WHERE `id`='2'

deleteAll()

If you do not specify any condition, this method will delete ALL rows in the table.
For example to delete the user from user table based condition status is ‘active’ and age is greater than to 20.

Sample1

User::deleteAll('status = :status AND age > :age', [':age' => 20, ':status' => 'active']);
//Output Query
//DELETE FROM `tbl_user` WHERE status = 'active' AND age > 20

Sample2

User::deleteAll(['and', 'type = :type_id', ['not in', 'usercategoryid', $categoriesList]], [
                    ':type_id' => 2
                ]);
//Output Query
//DELETE FROM `tbl_user` WHERE (type = 2) AND (`usercategoryid` NOT IN (1, 2, 3))