更新记录
使用 SQL
DatabaseQuery
类还提供用于构建更新查询的方法,特别是 update 和 set。我们还重用了在创建选择语句时使用过的另一个方法,即 where 方法。
$db = Factory::getContainer()->get('DatabaseDriver');
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
$db->quoteName('profile_value') . ' = :profile_value',
$db->quoteName('ordering') . ' = :ordering'
);
// Conditions for which records should be updated.
$conditions = array(
$db->quoteName('user_id') . ' = :user_id',
$db->quoteName('profile_key') . ' = :profile_key'
);
$query->update($db->quoteName('#__user_profiles'))->set($fields)->where($conditions);
$query
->bind(':profile_value', 'Updating custom message for user 1001.')
->bind(':ordering', 2, Joomla\Database\ParameterType::INTEGER)
->bind(':user_id', 42, Joomla\Database\ParameterType::INTEGER)
->bind(':profile_key', 'custom.message');
$db->setQuery($query);
$result = $db->execute();
使用对象
与 insertObject
类似,DatabaseDriver
类提供了一种更新对象的便捷方法。
下面我们将使用现有的 id 主键,使用新值更新我们的自定义表。
// Create an object for the record we are going to update.
$object = new stdClass();
// Must be a valid primary key value.
$object->id = 1;
$object->title = 'My Custom Record';
$object->description = 'A custom record being updated in the database.';
// Update their details in the users table using id as the primary key.
$result = Factory::getContainer()->get('DatabaseDriver')->updateObject('#__custom_table', $object, 'id');
就像 insertObject
一样,updateObject
为我们处理了转义表名。
如果在将记录更新到数据库表时出现问题,updateObject
方法将抛出错误。
在尝试更新记录之前,我们需要确保该记录已存在,因此我们可能会在执行 updateObject
方法之前添加某种类型的记录检查。