本文實例講述了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常見數據庫操作技巧匯總》
希望本文所述對大家基於Yii框架的PHP程序設計有所幫助。