加载中...

Yii-- DeleteAll连表删除报错问题的解决方法


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

页面代码为

  1. $criteria=new CDbCriteria;
  2. $criteria->join = ' LEFT JOIN {{positions}} p ON p.zpo_id=t.zpo_id ';
  3. $criteria->addCondition("p.zpo_type=1");
  4. $criteria->addCondition("t.zpl_content_id in ($id)");
  5. PosLog::model()->deleteAll($criteria);
错误SQL为
  1. 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语句应为
  1. 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 基类

  1. framework/db/schema/CDbCommandBuilder.php#166
  1. public function createDeleteCommand($table,$criteria)
  2. {
  3. $this->ensureTable($table);
  4. $sql="DELETE FROM {$table->rawName}";
  5. $sql=$this->applyJoin($sql,$criteria->join);
  6. $sql=$this->applyCondition($sql,$criteria->condition);
  7. $sql=$this->applyGroup($sql,$criteria->group);
  8. $sql=$this->applyHaving($sql,$criteria->having);
  9. $sql=$this->applyOrder($sql,$criteria->order);
  10. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  11. $command=$this->_connection->createCommand($sql);
  12. $this->bindValues($command,$criteria->params);
  13. return $command;
  14. }
解决方案。修改基类方法
  1. public function createDeleteCommand($table,$criteria,$alias='t')
  2. {
  3. $this->ensureTable($table);
  4.  
  5. $alias=$this->_schema->quoteTableName($alias);
  6. if(empty($criteria->join)){
  7. $sql="DELETE FROM {$table->rawName}";
  8. }else{
  9. $sql="DELETE $alias FROM {$table->rawName} $alias";
  10. }
  11. $sql=$this->applyJoin($sql,$criteria->join);
  12. $sql=$this->applyCondition($sql,$criteria->condition);
  13. $sql=$this->applyGroup($sql,$criteria->group);
  14. $sql=$this->applyHaving($sql,$criteria->having);
  15. $sql=$this->applyOrder($sql,$criteria->order);
  16. $sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
  17. $command=$this->_connection->createCommand($sql);
  18. $this->bindValues($command,$criteria->params);
  19. return $command;
  20. }


还没有评论.