Yii使用DeleteAll连表删除出现报错问题的解决方法

删除数据的时候,经常会遇到连联判断删除数据的条件,今天用Yii 的CDbCriteria生成关连条件。批量删除的时候数据库报错。

页面代码为:

$criteria=new CDbCriteria; $criteria->join = ' LEFT JOIN {{positions}} p ON p.zpo_id=t.zpo_id '; $criteria->addCondition("p.zpo_type=1"); $criteria->addCondition("t.zpl_content_id in ($id)"); PosLog::model()->deleteAll($criteria);

错误SQL为:

复制代码 代码如下:

DELETE FROM `zd_pos_log` LEFT JOIN zd_positions p ON p.zpo_id=t.zpo_id WHERE (p.zpo_type=1) AND (t.zpl_content_id in (76))

正确SQL语句应为:

复制代码 代码如下:

DELETE t FROM `zd_pos_log` t LEFT JOIN zd_positions p ON p.zpo_id=t.zpo_id WHERE (p.zpo_type=1) AND (t.zpl_content_id in (76))

追溯到Yii 基类:

framework/db/schema/CDbCommandBuilder.php#166

public function createDeleteCommand($table,$criteria) { $this->ensureTable($table); $sql="DELETE FROM {$table->rawName}"; $sql=$this->applyJoin($sql,$criteria->join); $sql=$this->applyCondition($sql,$criteria->condition); $sql=$this->applyGroup($sql,$criteria->group); $sql=$this->applyHaving($sql,$criteria->having); $sql=$this->applyOrder($sql,$criteria->order); $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset); $command=$this->_connection->createCommand($sql); $this->bindValues($command,$criteria->params); return $command; }

解决方案。修改基类方法:

public function createDeleteCommand($table,$criteria,$alias='t') { $this->ensureTable($table); $alias=$this->_schema->quoteTableName($alias); if(empty($criteria->join)){ $sql="DELETE FROM {$table->rawName}"; }else{ $sql="DELETE $alias FROM {$table->rawName} $alias"; } $sql=$this->applyJoin($sql,$criteria->join); $sql=$this->applyCondition($sql,$criteria->condition); $sql=$this->applyGroup($sql,$criteria->group); $sql=$this->applyHaving($sql,$criteria->having); $sql=$this->applyOrder($sql,$criteria->order); $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset); $command=$this->_connection->createCommand($sql); $this->bindValues($command,$criteria->params); return $command; }

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/5b64258602dd35b61fccda3f85a9131e.html