本文实例讲述了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框架的PHP程序设计有所帮助。
更多Yii使用DeleteAll连表删除出现报错问题的解决方法相关文章请关注PHP中文网!