以下代码直接来自文档,应在“test”表中插入一行。
$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()。这令人费解。
任何人都有见解?
答案 0 :(得分:3)
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。