本文實(shí)例講述了Yii使用DeleteAll連表刪除出現(xiàn)報(bào)錯(cuò)問題的解決方法。分享給大家供大家參考,具體如下:
刪除數(shù)據(jù)的時(shí)候,經(jīng)常會(huì)遇到連聯(lián)判斷刪除數(shù)據(jù)的條件,今天用Yii 的CDbCriteria生成關(guān)連條件。批量刪除的時(shí)候數(shù)據(jù)庫報(bào)錯(cuò)。
頁面代碼為:
$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);
錯(cuò)誤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語句應(yīng)為:
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))
追溯到Y(jié)ii 基類:
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;
}
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。