3
以下代碼是直接從文檔,並應插入一行到「測試」表。Joomla 1.5 - JTable查詢總是在執行更新,而不是INSERT
$row = &JTable::getInstance('test', 'Table');
if (!$row->bind(array('user_id'=>123, 'customer_id'=>1234))) {
return JError::raiseWarning(500, $row->getError());
}
if (!$row->store()) {
JError::raiseError(500, $row->getError());
}
我的表類看起來是這樣的:
class TableTest extends JTable
{
var $user_id = null;
var $customer_id = null;
function __construct(&$db)
{
parent::__construct('#__ipwatch', 'user_id', $db);
}
}
SELECT
查詢做工精細,但不INSERT
的。通過調試,我發現正在執行的查詢是UPDATE jos_test SET customer_id='1234' WHERE user_id='123'
,由於該行在數據庫中尚不存在而失敗(應爲INSERT
而不是UPDATE
)。
雖然挖過的Joomla的代碼,我發現這一點:
function __construct($table, $key, &$db)
{
$this->_tbl = $table;
$this->_tbl_key = $key;
$this->_db =& $db;
}
.....
.....
function store($updateNulls=false)
{
$k = $this->_tbl_key;
if($this->$k)
{
$ret = $this->_db->updateObject($this->_tbl, $this, $this->_tbl_key, $updateNulls);
}
else
{
$ret = $this->_db->insertObject($this->_tbl, $this, $this->_tbl_key);
}
if(!$ret)
{
$this->setError(get_class($this).'::store failed - '.$this->_db->getErrorMsg());
return false;
}
else
{
return true;
}
}
_tbl_key
這裏是「user_ID的」我在我的TableTest類過去了,所以它會出現,它總是會調用updateObject()當這個鍵被設置時。這是令人困惑的。
任何人有任何見解?
啊是的,問題是我沒有使用自動遞增主鍵(因爲我的表將現有用戶ID與客戶ID關聯),所以傳遞user_id導致UPDATE查詢。因爲我需要指定我的主鍵值,所以我通過直接調用'insertObject'來攻擊一個解決方法 – bcoughlan 2012-03-05 21:33:43
^^^而且這個解決方法在Joomla 2.5中破解了,所以我屈服了並且在表中使用了一個主鍵。 – bcoughlan 2012-04-05 05:43:59