Yii deleteByAttributs 用法,慎用Dao的delete
Yii框架一定要慎用Dao的delete,一不小心它生不成条件的话,就变成了整表删除。
可以用ActiveRecord的deleteByAttributes或deleteAll方法相对不容易写错。
deleteByAttributes用法如下:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy3321')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy3321>MyClass::model()->deleteAllByAttributes(array(
'phone_number'=>$phoneNumber,
));
或者第一个参数为空,使用第二个条件参数
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy1593')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy1593>MyClass::model()->deleteAllByAttributes(array(),'`phone_number` = :phone_number',array(
':phone_number'=>$phoneNumber,
));
或者使用deleteAll():
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9662')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy9662>MyClass::model()->deleteAll('`phone_number` = :phone_number',array(
':phone_number'=>$phoneNumber,
));
再来一个带in条件的
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy6735')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy6735>$condition = new CDbCriteria();
$condition->addCondition('status=:status');
$condition->params = array(':status'=>1);
$condition->addInCondition('user_id',array(100111,100221,100221));
User::model()->deleteAll($condition);Dao带in条件的示例
Yii::app()->db->createCommand()
->delete('mw_user', array('and', 'user_id=:user_id', array('in', 'position_id', array(1,2,3))),array(':user_id'=>121111));
但是请慎用DAO的delete,当你的条件写错一点,它将无法生成where条件,同时sql语句中也没有了where,但还不一定报错,结果就成了没有where的delete,结果会是整表被删除了。
您可能感兴趣的文章:
Yii deleteByAttributs 用法,慎用Dao的delete
yii框架builder、update、delete用法示例
yii中使用memcache的实例分享
php面向对象框架有哪些
Yii-自定义删除确认弹框(zyd)jquery实现代码
php静态类的罪与罚(原理详解与实例分析)
YII中assets的使用示例
yii框架如何通过控制台命令创建定时任务
TimerTask之spring静态注入的测试
yiic命令时提示“php.exe”不是内部或外部命令解决办法