本文整理汇总了PHP中Drupal\Core\Database\Connection::update方法的典型用法代码示例。如果您正苦于以下问题:PHP Connection::update方法的具体用法?PHP Connection::update怎么用?PHP Connection::update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Database\Connection
的用法示例。
在下文中一共展示了Connection::update方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: save
/**
* {@inheritdoc}
*/
public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
{
if ($source[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $source));
}
if ($alias[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Alias path %s has to start with a slash.', $alias));
}
$fields = array('source' => $source, 'alias' => $alias, 'langcode' => $langcode);
// Insert or update the alias.
if (empty($pid)) {
$query = $this->connection->insert('url_alias')->fields($fields);
$pid = $query->execute();
$fields['pid'] = $pid;
$operation = 'insert';
} else {
// Fetch the current values so that an update hook can identify what
// exactly changed.
$original = $this->connection->query('SELECT source, alias, langcode FROM {url_alias} WHERE pid = :pid', array(':pid' => $pid))->fetchAssoc();
$fields['pid'] = $pid;
$query = $this->connection->update('url_alias')->fields($fields)->condition('pid', $pid);
$pid = $query->execute();
$fields['original'] = $original;
$operation = 'update';
}
if ($pid) {
// @todo Switch to using an event for this instead of a hook.
$this->moduleHandler->invokeAll('path_' . $operation, array($fields));
Cache::invalidateTags(['route_match']);
return $fields;
}
return FALSE;
}
示例2: update
/**
* {@inheritdoc}
*/
public function update(array $batch)
{
try {
$this->connection->update('batch')->fields(array('batch' => serialize($batch)))->condition('bid', $batch['id'])->execute();
} catch (\Exception $e) {
$this->catchException($e);
}
}
示例3: update
/**
* {@inheritdoc}
*/
public function update($entry)
{
$count = NULL;
try {
$count = $this->connection->update('dbtng_example')->fields($entry)->condition('pid', $entry['pid'])->execute();
} catch (\Exception $e) {
drupal_set_message(t('db_update failed. Message = %message, query= %query', array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
}
return $count;
}
示例4: updateIndex
/**
* {@inheritdoc}
*/
public function updateIndex(NodeInterface $node)
{
$nid = $node->id();
$count = $this->database->query("SELECT COUNT(cid) FROM {comment_field_data} c INNER JOIN {forum_index} i ON c.entity_id = i.nid WHERE c.entity_id = :nid AND c.field_name = 'comment_forum' AND c.entity_type = 'node' AND c.status = :status AND c.default_langcode = 1", array(':nid' => $nid, ':status' => CommentInterface::PUBLISHED))->fetchField();
if ($count > 0) {
// Comments exist.
$last_reply = $this->database->queryRange("SELECT cid, name, created, uid FROM {comment_field_data} WHERE entity_id = :nid AND field_name = 'comment_forum' AND entity_type = 'node' AND status = :status AND default_langcode = 1 ORDER BY cid DESC", 0, 1, array(':nid' => $nid, ':status' => CommentInterface::PUBLISHED))->fetchObject();
$this->database->update('forum_index')->fields(array('comment_count' => $count, 'last_comment_timestamp' => $last_reply->created))->condition('nid', $nid)->execute();
} else {
// Comments do not exist.
// @todo This should be actually filtering on the desired node language
$this->database->update('forum_index')->fields(array('comment_count' => 0, 'last_comment_timestamp' => $node->getCreatedTime()))->condition('nid', $nid)->execute();
}
}
示例5: decrementFlagCounts
/**
* Decrements count of flagged entities.
*
* @param \Drupal\flag\Event\FlaggingEvent $event
* The flagging Event.
*/
public function decrementFlagCounts(FlaggingEvent $event) {
/* @var \Drupal\flag\FlaggingInterface flag */
$flag = $event->getFlag();
/* @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $event->getEntity();
$count_result = $this->connection->select('flag_counts')
->fields(NULL, ['flag_id', 'entity_id', 'entity_type', 'count'])
->condition('flag_id', $flag->id())
->condition('entity_id', $entity->id())
->condition('entity_type', $entity->getEntityTypeId())
->execute()
->fetchAll();
if ($count_result[0]->count == '1') {
$this->connection->delete('flag_counts')
->condition('flag_id', $flag->id())
->condition('entity_id', $entity->id())
->condition('entity_type', $entity->getEntityTypeId())
->execute();
}
else {
$this->connection->update('flag_counts')
->expression('count', 'count - 1')
->condition('flag_id', $flag->id())
->condition('entity_id', $entity->id())
->condition('entity_type', $entity->getEntityTypeId())
->execute();
}
$this->resetLoadedCounts($entity, $flag);
}
示例6: checkVersion
/**
* Checks whether the string version matches a given version, fix it if not.
*
* @param \Drupal\locale\StringInterface $string
* The string object.
* @param string $version
* Drupal version to check against.
*/
protected function checkVersion($string, $version)
{
if ($string->getId() && $string->getVersion() != $version) {
$string->setVersion($version);
$this->connection->update('locales_source', $this->options)->condition('lid', $string->getId())->fields(array('version' => $version))->execute();
}
}
示例7: update
/**
* {@inheritdoc}
*/
public function update(CommentInterface $comment)
{
// Allow bulk updates and inserts to temporarily disable the maintenance of
// the {comment_entity_statistics} table.
if (!$this->state->get('comment.maintain_entity_statistics')) {
return;
}
$query = $this->database->select('comment_field_data', 'c');
$query->addExpression('COUNT(cid)');
$count = $query->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->execute()->fetchField();
if ($count > 0) {
// Comments exist.
$last_reply = $this->database->select('comment_field_data', 'c')->fields('c', array('cid', 'name', 'changed', 'uid'))->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->orderBy('c.created', 'DESC')->range(0, 1)->execute()->fetchObject();
// Use merge here because entity could be created before comment field.
$this->database->merge('comment_entity_statistics')->fields(array('cid' => $last_reply->cid, 'comment_count' => $count, 'last_comment_timestamp' => $last_reply->changed, 'last_comment_name' => $last_reply->uid ? '' : $last_reply->name, 'last_comment_uid' => $last_reply->uid))->keys(array('entity_id' => $comment->getCommentedEntityId(), 'entity_type' => $comment->getCommentedEntityTypeId(), 'field_name' => $comment->getFieldName()))->execute();
} else {
// Comments do not exist.
$entity = $comment->getCommentedEntity();
// Get the user ID from the entity if it's set, or default to the
// currently logged in user.
if ($entity instanceof EntityOwnerInterface) {
$last_comment_uid = $entity->getOwnerId();
}
if (!isset($last_comment_uid)) {
// Default to current user when entity does not implement
// EntityOwnerInterface or author is not set.
$last_comment_uid = $this->currentUser->id();
}
$this->database->update('comment_entity_statistics')->fields(array('cid' => 0, 'comment_count' => 0, 'last_comment_timestamp' => $entity instanceof EntityChangedInterface ? $entity->getChangedTime() : REQUEST_TIME, 'last_comment_name' => '', 'last_comment_uid' => $last_comment_uid))->condition('entity_id', $comment->getCommentedEntityId())->condition('entity_type', $comment->getCommentedEntityTypeId())->condition('field_name', $comment->getFieldName())->execute();
}
// Reset the cache of the commented entity so that when the entity is loaded
// the next time, the statistics will be loaded again.
$this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache(array($comment->getCommentedEntityId()));
}
示例8: acquire
/**
* {@inheritdoc}
*/
public function acquire($name, $timeout = 30.0)
{
// Insure that the timeout is at least 1 ms.
$timeout = max($timeout, 0.001);
$expire = microtime(TRUE) + $timeout;
if (isset($this->locks[$name])) {
// Try to extend the expiration of a lock we already acquired.
$success = (bool) $this->database->update('semaphore')->fields(array('expire' => $expire))->condition('name', $name)->condition('value', $this->getLockId())->execute();
if (!$success) {
// The lock was broken.
unset($this->locks[$name]);
}
return $success;
} else {
// Optimistically try to acquire the lock, then retry once if it fails.
// The first time through the loop cannot be a retry.
$retry = FALSE;
// We always want to do this code at least once.
do {
try {
$this->database->insert('semaphore')->fields(array('name' => $name, 'value' => $this->getLockId(), 'expire' => $expire))->execute();
// We track all acquired locks in the global variable.
$this->locks[$name] = TRUE;
// We never need to try again.
$retry = FALSE;
} catch (IntegrityConstraintViolationException $e) {
// Suppress the error. If this is our first pass through the loop,
// then $retry is FALSE. In this case, the insert failed because some
// other request acquired the lock but did not release it. We decide
// whether to retry by checking lockMayBeAvailable(). This will clear
// the offending row from the database table in case it has expired.
$retry = $retry ? FALSE : $this->lockMayBeAvailable($name);
} catch (\Exception $e) {
// Create the semaphore table if it does not exist and retry.
if ($this->ensureTableExists()) {
// Retry only once.
$retry = !$retry;
} else {
throw $e;
}
}
// We only retry in case the first attempt failed, but we then broke
// an expired lock.
} while ($retry);
}
return isset($this->locks[$name]);
}
示例9: invalidateAll
/**
* Implements Drupal\Core\Cache\CacheBackendInterface::invalidateAll().
*/
public function invalidateAll()
{
try {
$this->connection->update($this->bin)->fields(array('expire' => REQUEST_TIME - 1))->execute();
} catch (\Exception $e) {
$this->catchException($e);
}
}
示例10: testExceptions
/**
* Tests that exceptions thrown by workers are handled properly.
*/
public function testExceptions()
{
// Get the queue to test the normal Exception.
$queue = $this->container->get('queue')->get('cron_queue_test_exception');
// Enqueue an item for processing.
$queue->createItem(array($this->randomMachineName() => $this->randomMachineName()));
// Run cron; the worker for this queue should throw an exception and handle
// it.
$this->cron->run();
$this->assertEqual(\Drupal::state()->get('cron_queue_test_exception'), 1);
// The item should be left in the queue.
$this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
// Expire the queue item manually. system_cron() relies in REQUEST_TIME to
// find queue items whose expire field needs to be reset to 0. This is a
// Kernel test, so REQUEST_TIME won't change when cron runs.
// @see system_cron()
// @see \Drupal\Core\Cron::processQueues()
$this->connection->update('queue')->condition('name', 'cron_queue_test_exception')->fields(['expire' => REQUEST_TIME - 1])->execute();
$this->cron->run();
$this->assertEqual(\Drupal::state()->get('cron_queue_test_exception'), 2);
$this->assertEqual($queue->numberOfItems(), 0, 'Item was processed and removed from the queue.');
// Get the queue to test the specific SuspendQueueException.
$queue = $this->container->get('queue')->get('cron_queue_test_broken_queue');
// Enqueue several item for processing.
$queue->createItem('process');
$queue->createItem('crash');
$queue->createItem('ignored');
// Run cron; the worker for this queue should process as far as the crashing
// item.
$this->cron->run();
// Only one item should have been processed.
$this->assertEqual($queue->numberOfItems(), 2, 'Failing queue stopped processing at the failing item.');
// Check the items remaining in the queue. The item that throws the
// exception gets released by cron, so we can claim it again to check it.
$item = $queue->claimItem();
$this->assertEqual($item->data, 'crash', 'Failing item remains in the queue.');
$item = $queue->claimItem();
$this->assertEqual($item->data, 'ignored', 'Item beyond the failing item remains in the queue.');
// Test the requeueing functionality.
$queue = $this->container->get('queue')->get('cron_queue_test_requeue_exception');
$queue->createItem([]);
$this->cron->run();
$this->assertEqual(\Drupal::state()->get('cron_queue_test_requeue_exception'), 2);
$this->assertFalse($queue->numberOfItems());
}
示例11: write
/**
* {@inheritdoc}
*/
public function write(Profile $profile)
{
$args = ['token' => $profile->getToken(), 'parent' => $profile->getParentToken(), 'data' => base64_encode(serialize($profile->getCollectors())), 'ip' => $profile->getIp(), 'method' => $profile->getMethod(), 'url' => $profile->getUrl(), 'time' => $profile->getTime(), 'created_at' => time()];
try {
$query = $this->database->select('webprofiler', 'w')->fields('w', ['token']);
$query->condition('token', $profile->getToken());
$count = $query->countQuery()->execute()->fetchAssoc();
if ($count['expression']) {
$this->database->update('webprofiler')->fields($args)->condition('token', $profile->getToken())->execute();
} else {
$this->database->insert('webprofiler')->fields($args)->execute();
}
$status = TRUE;
} catch (\Exception $e) {
$status = FALSE;
}
return $status;
}
示例12: regenerate
/**
* {@inheritdoc}
*/
public function regenerate($destroy = FALSE, $lifetime = NULL)
{
global $user;
// Nothing to do if we are not allowed to change the session.
if (!$this->isEnabled() || $this->isCli()) {
return;
}
// We do not support the optional $destroy and $lifetime parameters as long
// as #2238561 remains open.
if ($destroy || isset($lifetime)) {
throw new \InvalidArgumentException('The optional parameters $destroy and $lifetime of SessionManager::regenerate() are not supported currently');
}
$is_https = $this->requestStack->getCurrentRequest()->isSecure();
$cookies = $this->requestStack->getCurrentRequest()->cookies;
if ($is_https && $this->isMixedMode()) {
$insecure_session_name = $this->getInsecureName();
$params = session_get_cookie_params();
$session_id = Crypt::randomBytesBase64();
// If a session cookie lifetime is set, the session will expire
// $params['lifetime'] seconds from the current request. If it is not set,
// it will expire when the browser is closed.
$expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
setcookie($insecure_session_name, $session_id, $expire, $params['path'], $params['domain'], FALSE, $params['httponly']);
$cookies->set($insecure_session_name, $session_id);
}
if ($this->isStarted()) {
$old_session_id = $this->getId();
}
session_id(Crypt::randomBytesBase64());
$this->getMetadataBag()->clearCsrfTokenSeed();
if (isset($old_session_id)) {
$params = session_get_cookie_params();
$expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0;
setcookie($this->getName(), $this->getId(), $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
$fields = array('sid' => Crypt::hashBase64($this->getId()));
if ($is_https) {
$fields['ssid'] = Crypt::hashBase64($this->getId());
// If the "secure pages" setting is enabled, use the newly-created
// insecure session identifier as the regenerated sid.
if ($this->isMixedMode()) {
$fields['sid'] = Crypt::hashBase64($session_id);
}
}
$this->connection->update('sessions')->fields($fields)->condition($is_https ? 'ssid' : 'sid', Crypt::hashBase64($old_session_id))->execute();
}
if (!$this->isStarted()) {
// Start the session when it doesn't exist yet.
// Preserve the logged in user, as it will be reset to anonymous
// by \Drupal\Core\Session\SessionHandler::read().
$account = $user;
$this->startNow();
$user = $account;
}
date_default_timezone_set(drupal_get_user_timezone());
}
示例13: garbageCollection
/**
* {@inheritdoc}
*/
public function garbageCollection()
{
try {
// Clean up the queue for failed batches.
$this->connection->delete(static::TABLE_NAME)->condition('created', REQUEST_TIME - 864000, '<')->condition('name', 'drupal_batch:%', 'LIKE')->execute();
// Reset expired items in the default queue implementation table. If that's
// not used, this will simply be a no-op.
$this->connection->update(static::TABLE_NAME)->fields(array('expire' => 0))->condition('expire', 0, '<>')->condition('expire', REQUEST_TIME, '<')->execute();
} catch (\Exception $e) {
$this->catchException($e);
}
}
示例14: save
/**
* {@inheritdoc}
*/
public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
{
if ($source[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $source));
}
if ($alias[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Alias path %s has to start with a slash.', $alias));
}
$fields = array('source' => $source, 'alias' => $alias, 'langcode' => $langcode);
// Insert or update the alias.
if (empty($pid)) {
$try_again = FALSE;
try {
$query = $this->connection->insert(static::TABLE)->fields($fields);
$pid = $query->execute();
} catch (\Exception $e) {
// If there was an exception, try to create the table.
if (!($try_again = $this->ensureTableExists())) {
// If the exception happened for other reason than the missing table,
// propagate the exception.
throw $e;
}
}
// Now that the table has been created, try again if necessary.
if ($try_again) {
$query = $this->connection->insert(static::TABLE)->fields($fields);
$pid = $query->execute();
}
$fields['pid'] = $pid;
$operation = 'insert';
} else {
// Fetch the current values so that an update hook can identify what
// exactly changed.
try {
$original = $this->connection->query('SELECT source, alias, langcode FROM {url_alias} WHERE pid = :pid', array(':pid' => $pid))->fetchAssoc();
} catch (\Exception $e) {
$this->catchException($e);
$original = FALSE;
}
$fields['pid'] = $pid;
$query = $this->connection->update(static::TABLE)->fields($fields)->condition('pid', $pid);
$pid = $query->execute();
$fields['original'] = $original;
$operation = 'update';
}
if ($pid) {
// @todo Switch to using an event for this instead of a hook.
$this->moduleHandler->invokeAll('path_' . $operation, array($fields));
Cache::invalidateTags(['route_match']);
return $fields;
}
return FALSE;
}
示例15: save
/**
* {@inheritdoc}
*/
public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
{
$fields = array('source' => $source, 'alias' => $alias, 'langcode' => $langcode);
// Insert or update the alias.
if (empty($pid)) {
$query = $this->connection->insert('url_alias')->fields($fields);
$pid = $query->execute();
$fields['pid'] = $pid;
$operation = 'insert';
} else {
$fields['pid'] = $pid;
$query = $this->connection->update('url_alias')->fields($fields)->condition('pid', $pid);
$pid = $query->execute();
$operation = 'update';
}
if ($pid) {
// @todo Switch to using an event for this instead of a hook.
$this->moduleHandler->invokeAll('path_' . $operation, array($fields));
return $fields;
}
return FALSE;
}