addField example


class AlterTest extends DatabaseTestBase {

  /** * Tests that we can do basic alters. */
  public function testSimpleAlter() {
    $query = $this->connection->select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
    $query->addTag('database_test_alter_add_range');

    $result = $query->execute()->fetchAll();

    $this->assertCount(2, $result, 'Returned the correct number of rows.');
  }

  /** * Tests that we can alter the joins on a query. */
  

namespace Tests\Support\Database\Migrations;

use CodeIgniter\Database\Migration;

class ExampleMigration extends Migration
{
    protected $DBGroup = 'tests';

    public function up()
    {
        $this->forge->addField('id');
        $this->forge->addField([
            'name'       => ['type' => 'varchar', 'constraint' => 31],
            'uid'        => ['type' => 'varchar', 'constraint' => 31],
            'class'      => ['type' => 'varchar', 'constraint' => 63],
            'icon'       => ['type' => 'varchar', 'constraint' => 31],
            'summary'    => ['type' => 'varchar', 'constraint' => 255],
            'created_at' => ['type' => 'datetime', 'null' => true],
            'updated_at' => ['type' => 'datetime', 'null' => true],
            'deleted_at' => ['type' => 'datetime', 'null' => true],
        ]);

        
$query->fields('n', ['nid']);

      $query->join('comment_entity_statistics', 'ces', "[n].[nid] = [ces].[entity_id] AND [ces].[field_name] = 'comment_forum' AND [ces].[entity_type] = 'node'");
      $query->fields('ces', [
        'cid',
        'last_comment_uid',
        'last_comment_timestamp',
        'comment_count',
      ]);

      $query->join('forum_index', 'f', '[f].[nid] = [n].[nid]');
      $query->addField('f', 'tid', 'forum_tid');

      $query->join('users_field_data', 'u', '[n].[uid] = [u].[uid] AND [u].[default_langcode] = 1');
      $query->addField('u', 'name');

      $query->join('users_field_data', 'u2', '[ces].[last_comment_uid] = [u2].[uid] AND [u].[default_langcode] = 1');

      $query->addExpression('CASE [ces].[last_comment_uid] WHEN 0 THEN [ces].[last_comment_name] ELSE [u2].[name] END', 'last_comment_name');

      $query
        ->orderBy('f.sticky', 'DESC')
        ->orderByHeader($header)
        
->fields('i18n')
      ->fields('lt', [
        'translation',
        'language',
        'plid',
        'plural',
      ])
      ->condition('i18n.type', 'field')
      ->condition('property', 'option\_%', 'LIKE');
    $query->innerJoin('locales_target', 'lt', '[lt].[lid] = [i18n].[lid]');
    $query->leftjoin('content_node_field', 'cnf', '[cnf].[field_name] = [i18n].[objectid]');
    $query->addField('cnf', 'field_name');
    $query->addField('cnf', 'global_settings');
    // Minimise changes to the d6_field_option_translation.yml, which is copied     // from d6_field.yml, by ensuring the 'type' property is from     // content_node_field table.     $query->addField('cnf', 'type');
    $query->addField('i18n', 'type', 'i18n_type');

    // The i18n_string module adds a status column to locale_target. It was     // originally 'status' in a later revision it was named 'i18n_status'.     /** @var \Drupal\Core\Database\Schema $db */
    if ($this->getDatabase()->schema()->fieldExists('locales_target', 'status')) {
      
'translate',
    ])
      ->fields('nr', [
        'title',
        'body',
        'teaser',
        'log',
        'timestamp',
        'format',
        'vid',
      ]);
    $query->addField('n', 'uid', 'node_uid');
    $query->addField('nr', 'uid', 'revision_uid');

    // If the content_translation module is enabled, get the source langcode     // to fill the content_translation_source field.     if ($this->moduleHandler->moduleExists('content_translation')) {
      $query->leftJoin('node', 'nt', '[n].[tnid] = [nt].[nid]');
      $query->addField('nt', 'language', 'source_langcode');
    }

    if (isset($this->configuration['node_type'])) {
      $query->condition('n.type', (array) $this->configuration['node_type'], 'IN');
    }
$query = $this->select('entity_translation', 'et')
      ->fields('et')
      ->fields('c', [
        'subject',
      ])
      ->condition('et.entity_type', 'comment')
      ->condition('et.source', '', '<>');

    $query->innerJoin('comment', 'c', '[c].[cid] = [et].[entity_id]');
    $query->innerJoin('node', 'n', '[n].[nid] = [c].[nid]');

    $query->addField('n', 'type', 'node_type');

    $query->orderBy('et.created');

    return $query;
  }

  /** * {@inheritdoc} */
  public function prepareRow(Row $row) {
    $cid = $row->getSourceProperty('entity_id');
    

class UserUid extends FilterPluginBase {

  public function query() {
    $this->ensureMyTable();

    $subselect = Database::getConnection()->select('comment_field_data', 'c');
    $subselect->addField('c', 'cid');
    $subselect->condition('c.uid', $this->value, $this->operator);

    $entity_id = $this->definition['entity_id'];
    $entity_type = $this->definition['entity_type'];
    $subselect->where("[c].[entity_id] = [$this->tableAlias].[$entity_id]");
    $subselect->condition('c.entity_type', $entity_type);

    $condition = ($this->view->query->getConnection()->condition('OR'))
      ->condition("$this->tableAlias.uid", $this->value, $this->operator)
      ->exists($subselect);

    

    }

    // If $field contains characters which are not allowed in a field name     // it is considered an expression, these can't be handled automatically     // either.     if ($this->connection->escapeField($field) != $field) {
      return $this;
    }

    // This is a case that can be handled automatically, add the field.     $this->addField(NULL, $field);
    return $this;
  }

  /** * {@inheritdoc} */
  public function addExpression($expression$alias = NULL, $arguments = []) {
    if (empty($alias)) {
      $alias = 'expression';
    }

    
  // function hook_update_N() {
  // Example function body for adding a field to a database table, which does   // not require a batch operation:   $spec = [
    'type' => 'varchar',
    'description' => "New Col",
    'length' => 20,
    'not null' => FALSE,
  ];
  $schema = Database::getConnection()->schema();
  $schema->addField('my_table', 'newcol', $spec);

  // Example of what to do if there is an error during your update.   if ($some_error_condition_met) {
    throw new UpdateException('Something went wrong; here is what you should do.');
  }

  // Example function body for a batch update. In this example, the values in   // a database field are updated.   if (!isset($sandbox['progress'])) {
    // This must be the first run. Initialize the sandbox.     $sandbox['progress'] = 0;
    
/** * Add Field * * @param array|string $field * * @return Forge */
    public function addField($field)
    {
        if (is_string($field)) {
            if ($field === 'id') {
                $this->addField([
                    'id' => [
                        'type'           => 'INT',
                        'constraint'     => 9,
                        'auto_increment' => true,
                    ],
                ]);
                $this->addKey('id', true);
            } else {
                if (strpos($field, ' ') === false) {
                    throw new InvalidArgumentException('Field information is required for that operation.');
                }

                
$this->set(new Field\InputFormField($this->button));
            }
        }

        // find form elements corresponding to the current form         if ($this->node->hasAttribute('id')) {
            // corresponding elements are either descendants or have a matching HTML5 form attribute             $formId = Crawler::xpathLiteral($this->node->getAttribute('id'));

            $fieldNodes = $xpath->query(sprintf('( descendant::input[@form=%s] | descendant::button[@form=%1$s] | descendant::textarea[@form=%1$s] | descendant::select[@form=%1$s] | //form[@id=%1$s]//input[not(@form)] | //form[@id=%1$s]//button[not(@form)] | //form[@id=%1$s]//textarea[not(@form)] | //form[@id=%1$s]//select[not(@form)] )[not(ancestor::template)]', $formId));
            foreach ($fieldNodes as $node) {
                $this->addField($node);
            }
        } else {
            // do the xpath query with $this->node as the context node, to only find descendant elements             // however, descendant elements with form attribute are not part of this form             $fieldNodes = $xpath->query('( descendant::input[not(@form)] | descendant::button[not(@form)] | descendant::textarea[not(@form)] | descendant::select[not(@form)] )[not(ancestor::template)]', $this->node);
            foreach ($fieldNodes as $node) {
                $this->addField($node);
            }
        }

        if ($this->baseHref && '' !== $this->node->getAttribute('action')) {
            
class VocabularyTranslation extends DrupalSqlBase {

  /** * {@inheritdoc} */
  public function query() {
    $query = $this->select('vocabulary', 'v')
      ->fields('v')
      ->fields('i18n', ['lid', 'type', 'property', 'objectid'])
      ->fields('lt', ['lid', 'translation'])
      ->condition('i18n.type', 'vocabulary');
    $query->addField('lt', 'language', 'lt.language');
    // The i18n_strings table has two columns containing the object ID, objectid     // and objectindex. The objectid column is a text field. Therefore, for the     // join to work in PostgreSQL, use the objectindex field as this is numeric     // like the vid field.     $query->join('i18n_strings', 'i18n', '[v].[vid] = [i18n].[objectindex]');
    $query->innerJoin('locales_target', 'lt', '[lt].[lid] = [i18n].[lid]');

    return $query;
  }

  /** * {@inheritdoc} */

  protected function summaryQuery() {
    if (empty($this->definition['many to one'])) {
      $this->ensureMyTable();
    }
    else {
      $this->tableAlias = $this->helper->summaryJoin();
    }

    if (empty($this->options['glossary'])) {
      // Add the field.       $this->base_alias = $this->query->addField($this->tableAlias, $this->realField);
      $this->query->setCountField($this->tableAlias, $this->realField);
    }
    else {
      // Add the field.       $formula = $this->getFormula();
      $this->base_alias = $this->query->addField(NULL, $formula$this->field . '_truncated');
      $this->query->setCountField(NULL, $formula$this->field, $this->field . '_truncated');
    }

    $this->summaryNameField();
    return $this->summaryBasics(FALSE);
  }

class Comment extends FieldableEntity {

  /** * {@inheritdoc} */
  public function query() {
    $query = $this->select('comment', 'c')->fields('c');
    $query->innerJoin('node', 'n', '[c].[nid] = [n].[nid]');
    $query->addField('n', 'type', 'node_type');
    $query->orderBy('c.created');
    return $query;
  }

  /** * {@inheritdoc} */
  public function prepareRow(Row $row) {
    $cid = $row->getSourceProperty('cid');

    $node_type = $row->getSourceProperty('node_type');
    

    public function ensureTable()
    {
        if ($this->tableChecked || $this->db->tableExists($this->table)) {
            return;
        }

        $forge = Database::forge($this->db);

        $forge->addField([
            'id' => [
                'type'           => 'BIGINT',
                'constraint'     => 20,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'version' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
                'null'       => false,
            ],
            
Home | Imprint | This part of the site doesn't use cookies.