它看起來像你使用到Zend_Db_Adapter會執行您的查詢,所以我不知道你可以做我做什麼,反正在這裏不用。
我通常使用Zend_Db_Table_Row save()方法插入和更新記錄,但是我也使用DbTable模型來提供對Table和Table_Row抽象api的訪問。
public function save(Music_Model_Artist $artist) {
//if id is not null
if (!is_null($artist->id)) {
//find row, uses fetchRow() so will return NULL if not found
$row = $this->findById($artist->id);
$row->id = $artist->id;
} else {
//if ID is null create new row
$row = $this->_getGateway()->createRow();
}
//assign data to row
$row->name = $artist->name;
//save new row or update
$row->save();
//return the row, in case I need it for something else
return $row;
}
什麼這相當於是,如果我包括與所述數據陣列中的ID(或在這種情況下的實體對象)的行將被更新,並且如果沒有ID的對象的新行會創建。
如果你好奇,這裏就是我__construct類:
public function __construct(Zend_Db_Table_Abstract $tableGateway = NULL) {
//pass in concrete DbTable Model, parent alts to using table name string to construct class
$this->_tableGateway = new Application_Model_DbTable_Artist();
parent::__construct($tableGateway);
}
希望這提供了一些幫助。
Thanks max。從09年開始,這是一個問題嗎?這是一個非常常見的編程實踐,必須有一種方法來做到這一點。 –
我可以明白爲什麼你認爲這可能是「更安全」,但是如果你真的擔心你的where子句不是唯一標識一條記錄,你應該在更新和報告錯誤條件之前實際檢查數據,而不是留下破損,數據庫中的數據不一致。如果你不能相信你的主鍵是獨一無二的,你就會遇到比意外更新多個表更大的問題。 –
是的肖恩真的是事實,而這在邏輯失敗的情況下更是一個限制性的災難,但實際上是不必要的。 –