Yii Framework 2 : Delete Query

Model delete()

$model = User::find($id);

delete() With Condition

        ->delete('tbl_user', 'status = 0')

delete() With Query

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

delete() With Prepared Statements

Sample 1:

$model = $connection->createCommand('DELETE FROM tbl_user WHERE userid=:userid');
$model->bindParam(':userid', $userid);
$userid = 5;
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;
//delete user 2
$userid = 2;

find() And Delete()


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


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.

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

            '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))

  • Bashir ahmad

    “message”: “Undefined variable: connection”, i am facing this error. I am not getting what this connection variable is for. Please help

  • Mohd Sameer

    Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails?
    how to manage this message

    • Arif Rahman Hakim

      make your relation type delete cascade

  • Shamnad Meerasahib

    How to join another table in deleteAll query