开门见山。
我需要更新数据库中的一个字段,使用该字段首先计算新值。
例如字段:/image/FADH6.jpg
现在我正在使用 Joomla updateObject 函数。我的目标是在不使用 select 语句的情况下从数据库表中获取“已用”值。
然后我需要用它计算一个新值,例如 (spent + 10.00) 并用新值更新字段。查看下面的代码:
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($object->spent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
我需要进行计算的位是
$object->spent = ($object->spent - $item['total']);
我意识到我可以使用单独的插入语句,但我想知道是否有更好的方法。非常感谢任何帮助。
它需要像这样工作,没有选择(工作示例)
$query = $db->getQuery(true);
$query->select($db->quoteName('spent'));
$query->from($db->quoteName('#__mytable'));
$query->where($db->quoteName('catid')." = ". $item['category']);
// Reset the query using our newly populated query object.
$db->setQuery($query);
$oldspent = $db->loadResult();
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->catid = $item['category'];
$object->spent = ($oldspent - $item['total']);
// Update their details in the users table using id as the primary key.
$result = JFactory::getDbo()->updateObject('#__mytable', $object, 'catid');
最佳答案
尝试使用 updateObject('#__mytable', $object, 'catid');
的关键点是您的查询逻辑需要引用计算中的列名称来分配“差异”作为新值。用该值减去另一个值来更新列值的原始 mysql 查询语法如下:
"`spent` = `spent` - {$item['total']}"
updateObject()
会将 spent - {$item['total']}
转换为文字字符串,数据库将期望一个数值,因此 UPDATE 结果为记录了 0
值。换句话说,$db->getAffectedRows()
将为您提供正计数,并且不会生成错误,但您不会获得所需的数学操作。
解决方法是放弃 updateObject()
作为工具并构建一个没有对象的 UPDATE 查询 - 不要担心它不会太复杂。我将构建一些诊断和故障检查,但您可以删除您想要的任何部分。
我已经在我的本地主机上测试了以下代码是否成功:
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true)
->update($db->quoteName('#__mytable'))
->set($db->quoteName("price") . " = " . $db->qn("price") . " - " . (int)$item['total'])
->where($db->quoteName("catid") . " = " . (int)$item['category']);
echo $query->dump(); // see the generated query (but don't show to public)
$db->setQuery($query);
$db->execute();
if ($affrows = $db->getAffectedRows()) {
JFactory::getApplication()->enqueueMessage("Updated. Affected Rows: $affrows", 'success');
} else {
JFactory::getApplication()->enqueueMessage("Logic Error", 'error');
}
} catch (Exception $e) {
JFactory::getApplication()->enqueueMessage("Query Syntax Error: " . $e->getMessage(), 'error'); // never show getMessage() to public
}
这里是一个讨论 mysql 减法逻辑的 StackOverflow 页面:update a column by subtracting a value
关于model-view-controller - 使用 Joomla UpdateObject 方法使用同一表中的计算字段更新数据库字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317627/