Skip to content

[8.x] Fix duplicated columns on select#37936

Closed
gerardojbaez wants to merge 1 commit into
laravel:8.xfrom
gerardojbaez:fix-select-duplicated-columns
Closed

[8.x] Fix duplicated columns on select#37936
gerardojbaez wants to merge 1 commit into
laravel:8.xfrom
gerardojbaez:fix-select-duplicated-columns

Conversation

@gerardojbaez
Copy link
Copy Markdown

Description

Using $query->addSelect('something') multiple times introduces duplicated columns, causing SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'something'.

Steps to reproduce

Execute the following query:

// accounts() is a many-to-many relation, with an intermediate Eloquent Model
App\User::find(1)->accounts()->groupBy('accounts.id')->select('accounts.*')->paginate();

The resulting problematic SQL query will be:

select count(*) as aggregate
from (select `accounts`.*,
             `accounts`.*,
             `membership`.`user_id`    as `pivot_user_id`,
             `membership`.`account_id` as `pivot_account_id`,
             `membership`.`id`         as `pivot_id`,
             `membership`.`created_at` as `pivot_created_at`,
             `membership`.`updated_at` as `pivot_updated_at`
      from `accounts`
               inner join `membership` on `accounts`.`id` = `membership`.`account_id`
      where `membership`.`user_id` = 1
      group by `accounts`.`id`) as `aggregate_table`

The second accounts.* is introduced by paginate() here:

/**
* Set the select clause for the relation query.
*
* @param array $columns
* @return array
*/
protected function shouldSelect(array $columns = ['*'])
{
if ($columns == ['*']) {
$columns = [$this->related->getTable().'.*'];
}
return array_merge($columns, [$this->getQualifiedFirstKeyName().' as laravel_through_key']);
}

Related to #34096 #34097

@taylorotwell
Copy link
Copy Markdown
Member

This can leave the keys out of numerical order which may have unexpected results in some situations. May want to review this.

@gerardojbaez
Copy link
Copy Markdown
Author

You are right.

The issue is not a big deal and can be prevented on our end by passing an empty array to the paginate method: $query->paginate(15, []); this will prevent shouldSelect from adding the duplicated column.

Let me know should you want me to submit another improved solution.

Thanks!

@linaspasv
Copy link
Copy Markdown
Contributor

Hm, calling $query->paginate(15, []) does not prevent duplicate column. Is there any solution for the problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants