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