function InsertTest::testInsertSelectFields

Same name in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Database/InsertTest.php \Drupal\KernelTests\Core\Database\InsertTest::testInsertSelectFields()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Database/InsertTest.php \Drupal\KernelTests\Core\Database\InsertTest::testInsertSelectFields()
  3. 10 core/tests/Drupal/KernelTests/Core/Database/InsertTest.php \Drupal\KernelTests\Core\Database\InsertTest::testInsertSelectFields()

Tests that the INSERT INTO ... SELECT (fields) ... syntax works.

File

core/tests/Drupal/KernelTests/Core/Database/InsertTest.php, line 157

Class

InsertTest
Tests the insert builder.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testInsertSelectFields() : void {
    $query = $this->connection
        ->select('test_people', 'tp');
    // The query builder will always append expressions after fields.
    // Add the expression first to test that the insert fields are correctly
    // re-ordered.
    $query->addExpression('[tp].[age]', 'age');
    $query->fields('tp', [
        'name',
        'job',
    ])
        ->condition('tp.name', 'Meredith');
    // The resulting query should be equivalent to:
    // INSERT INTO test (age, name, job)
    // SELECT tp.age AS age, tp.name AS name, tp.job AS job
    // FROM test_people tp
    // WHERE tp.name = 'Meredith'
    $this->connection
        ->insert('test')
        ->from($query)
        ->execute();
    $saved_age = $this->connection
        ->query('SELECT [age] FROM {test} WHERE [name] = :name', [
        ':name' => 'Meredith',
    ])
        ->fetchField();
    $this->assertSame('30', $saved_age, 'Can retrieve after inserting.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.