首页 > PHP技术 > Yii2 > Yii2 删除
2015
12-24

Yii2 删除

直接 model 删除

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

带有条件的删除

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

使用 Query 查询删除

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

使用预处理语句删除

方法一

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

方法二

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

查找并且删除

$user = User::findOne(2);
$user->delete();
// 输出语句
// DELETE FROM `tbl_user` WHERE `id`='2'

deleteAll() 删除多个

如果你不指定任何条件下,该方法将删除表中的所有行。例如删除用户表中状态条件是 active 和年龄大于20的用户。

方法一

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

方法二

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

关注代码技巧免费领教程

代码技巧

查 看学习编程5个常见的疑问