Joomla 1.5-JTable查询总是执行更新而不是插入
下面的代码直接来自文档,应该在“test”表中插入一行 我的table类如下所示:Joomla 1.5-JTable查询总是执行更新而不是插入,joomla,joomla1.5,joomla-extensions,Joomla,Joomla1.5,Joomla Extensions,下面的代码直接来自文档,应该在“test”表中插入一行 我的table类如下所示: class TableTest extends JTable { var $user_id = null; var $customer_id = null; function __construct(&$db) { parent::__construct( '#__ipwatch', 'user_id', $db ); } } SELEC
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\u test SET customer\u id='1234',其中user\u 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;
}
}
\u tbl\u key
这是我在TableTest类中传递的“user\u 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()。这意味着,如果要存储新用户,则不能指定用户id。啊,是的,问题是我没有使用自动递增主键(因为我的表将现有用户id与客户id关联),因此传递用户id会导致更新查询。因为我需要指定主键值,所以我通过直接调用
insertObject
directly^^^^^^^破解了一个解决方案,这个解决方案在Joomla 2.5中中断了,所以我放弃了,在表中使用了主键。
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 );
}
// ...