【问题标题】:Joomla 1.5 - JTable queries always doing UPDATE instead of INSERTJoomla 1.5 - JTable 查询总是执行 UPDATE 而不是 INSERT
【发布时间】:2012-03-22 14:38:55
【问题描述】:

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

$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()。真是莫名其妙。

有人有什么见解吗?

【问题讨论】:

    标签: joomla joomla1.5 joomla-extensions


    【解决方案1】:
    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。

    【讨论】:

    • 啊,是的,问题是我没有使用自动递增的主键(因为我的表将现有用户 ID 与客户 ID 相关联),因此传递 user_id 会导致 UPDATE 查询。由于我需要指定我的主键值,我通过直接调用insertObject 破解了一个解决方法
    猜你喜欢
    • 2022-10-07
    • 2020-12-21
    • 1970-01-01
    • 2011-06-11
    • 2012-04-22
    • 2021-10-20
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多