直接 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))
扫码二维码 获取免费视频学习资料
- 本文固定链接: http://www.phpxs.com/post/4624/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料
查 看2022高级编程视频教程免费获取