insertFields example

/** * Confirms that we can merge-update a record successfully. * * This test varies from the previous test because it manually defines which * fields are inserted, and which fields are updated. */
  public function testMergeUpdateExcept() {
    $num_records_before = $this->connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();

    $this->connection->merge('test_people')
      ->key('job', 'Speaker')
      ->insertFields(['age' => 31])
      ->updateFields(['name' => 'Tiffany'])
      ->execute();

    $num_records_after = $this->connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();
    $this->assertEquals($num_records_before$num_records_after, 'Merge updated properly.');

    $person = $this->connection->query('SELECT * FROM {test_people} WHERE [job] = :job', [':job' => 'Speaker'])->fetch();
    $this->assertEquals('Tiffany', $person->name, 'Name set correctly.');
    $this->assertEquals(30, $person->age, 'Age skipped correctly.');
    $this->assertEquals('Speaker', $person->job, 'Job set correctly.');
  }

  
public function __construct(Connection $connection) {
    $this->connection = $connection;
  }

  /** * {@inheritdoc} */
  protected function doInvalidateTags(array $tags) {
    try {
      foreach ($tags as $tag) {
        $this->connection->merge('cachetags')
          ->insertFields(['invalidations' => 1])
          ->expression('invalidations', '[invalidations] + 1')
          ->key('tag', $tag)
          ->execute();
      }
    }
    catch (\Exception $e) {
      // Create the cache table, which will be empty. This fixes cases during       // core install where cache tags are invalidated before the table is       // created.       if (!$this->ensureTableExists()) {
        throw $e;
      }

  public function doSetIfNotExists($key$value) {
    $result = $this->connection->merge($this->table)
      ->insertFields([
        'collection' => $this->collection,
        'name' => $key,
        'value' => $this->serializer->encode($value),
      ])
      ->condition('collection', $this->collection)
      ->condition('name', $key)
      ->execute();
    return $result == Merge::STATUS_INSERT;
  }

  /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.