以下代码直接来自文档,应在“测试”表中插入一行。
$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
这里是我在 TableTest 类中传递的“user_id”,因此看起来它总是会在设置此键时调用 updateObject()。这令人费解。
有人有什么见解吗?
最佳答案
function store( $updateNulls=false )
{
// You set user_id so this branch is executed
if( $this->$k)
{
$ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls );
}
// ...
在我看来,查看代码时,store() 检查主键字段是否存在以及它是否使用 updateObject()。这意味着如果您想存储新用户,则不能指定 user_id。
关于Joomla 1.5 - JTable 查询总是执行更新而不是插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9561319/