active-record icon indicating copy to clipboard operation
active-record copied to clipboard

Calling yii\db\Query addSelect($fields) overwrites default select set

Open undestroyer opened this issue 7 years ago • 7 comments

What steps will reproduce the problem?

$query = ArClass::find();
$query->addSelect('extraField');
$item = $query->one();

What is the expected result?

$item has all default fields + 1 extraField, defined in addSelect()

What do you get instead?

$item has only extraField and does not have default fields.

Additional info

Q A
Yii version 2.0.13.1
PHP version 7.0.23
Operating system Ubuntu 16.04.3 x86_64
  1. Due to docs, select property means "all by default" yii\db\Query:58
 /**
  * @var array the columns being selected. For example, `['id', 'name']`.
  * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
  * @see select()
  */
public $select; 
  1. Add statement ignores defauls if I did not defined defaults again. yii\db\Query:592
if ($this->select === null) {
    $this->select = $columns;
} else {
    $this->select = array_merge($this->select, $columns);
}

Some use cases:

What I want How do I do Is goal Reached?
Select all default columns ArClass::find()->all() // no call select() yes
Select only 2 passed columns ArClass::find()->select(['col1', 'col2'])->all() yes
Select 2 passed columns +1 more ArClass::find()->select(['col1', 'col2'])->addSelect('col3')->all() yes
Select all default columns + 1 more ArClass::find()->addSelect('col3')->all() no
Select all default columns + 1 more ArClass::find()->select('*')->addSelect('col3')->all() sometimes
Select all default columns + 1 more ArClass::find()->select(ArClass::tableName() . '.*')->addSelect('col3')->all() yes

In my opinion, query must select all default columns until I define columns set manually. Add meand adding element to some set. $select defined as all by default, but when you call addSelect() without calling select(), that means default not exists, add this.

See also #12249

undestroyer avatar Dec 13 '17 03:12 undestroyer