Framework: Builder Select() alias as id problem

Created on 30 Nov 2018  路  10Comments  路  Source: laravel/framework

  • Laravel Version: 5.7.13
  • PHP Version: 7.1.3
  • Database Driver & Version: mysql 15.1

Query Builder function select() alias has a problem when I tried to alias a column name as id like below:
Airport::domestic()->select('iata as id', 'name as text')->get()
and I got this as result:
[ { id: 0, text: "John F. Kennedy International Airport" } ]
it returns id with 0 value which is not correct.
this is needed for select2 ajax default data format.

Most helpful comment

It's not a bug, you just can't use Eloquent like this.

A possible workaround is the base query builder:

$airports = Airport::domestic()->select('iata as id', 'name as text')->toBase()->get();

All 10 comments

Does your airports table have an actual id column?

@staudenmeir
yes, but it should not impact on result.

It does indirectly: Your model expects id to be an integer column (as it normally is), so the value gets cast to an integer (resulting in 0).

@staudenmeir
I tried another integer column and it resulted correctly with no casting. just id makes problem in results.

"Normal" integer columns only get cast when you add them to $casts. As id is the primary key, this happens automatically:

https://github.com/laravel/framework/blob/b24870a0e1fd9daefcd885abecd1a6f727b64a9b/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L905-L912

@staudenmeir
why it would impact on result? main column that I need to alias is iata not id.
when I alias it to plain text like id or anything else it should result just like raw sql results, but it doesn't.

The model doesn't know that id contains the value of iata.

@staudenmeir
I think it should know :) that's a bug.
that's why I'm here and reporting this.

It's not a bug, you just can't use Eloquent like this.

A possible workaround is the base query builder:

$airports = Airport::domestic()->select('iata as id', 'name as text')->toBase()->get();

@staudenmeir
you're right, thank you for response. It's worked correctly, many thanks.

Was this page helpful?
0 / 5 - 0 ratings