Joomla 1.5 - JTable 查询总是执行更新而不是插入

标签 joomla joomla1.5 joomla-extensions

以下代码直接来自文档,应在“测试”表中插入一行。

$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/

相关文章:

php - 外部页面中的 Joomla 菜单

php - 自定义和新员工的最佳 CMS?

php - 在 php/Joomla 中创建复选框过滤器

php - 在 Joomla 页面中编辑 HTML

php - 审计 Joomla! 1.5 系统健康和安全?

php - 迁移类别/部分到 joomla 2.5

css - 将自定义 css 添加到 Helix3 和 SP PageBuilder

Joomla - 如何让注册用户更改密码

mysql - 在将行导入 mySQL 之前如何检查值是否唯一?

php - 我可以将可执行的 PHP 代码插入 Joomla 自定义 HTML 模块吗?