Yii解决DeleteAll连表删除报错问题
程序员文章站
2022-04-06 18:59:12
...
本文主要介绍了Yii使用DeleteAll连表删除出现报错问题的解决方法,分析了相关的SQL语句及出现错误的原因与改正方法,需要的朋友可以参考下。希望对大家有所帮助。
具体如下:
删除数据的时候,经常会遇到连联判断删除数据的条件,今天用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解决DeleteAll连表删除报错问题的详细内容,更多请关注其它相关文章!