本文主要介紹了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連表刪除錯誤問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!