framework icon indicating copy to clipboard operation
framework copied to clipboard

[Bug] Query Builder lists not keyed to id by default

Open sq2 opened this issue 13 years ago • 9 comments

Query Builder lists are not keyed to the table id field by default. Only assuming this is a bug due to this statement in the docs (http://four.laravel.com/docs/queries#selects): This method will return an array of role titles, keyed by the role ID.

$roles = DB::table('roles')->lists('title');

Outputs numeric array keys:

array(
    0 => 'Admin',
    1 => 'Manager',
    2 => 'Editor'
);

Instead of table id keys like:

array(
    1 => 'Admin',
    2 => 'Manager',
    5 => 'Editor'
);

But this works fine:

$roles = DB::table('roles')->lists('title', 'id');

sq2 avatar Apr 18 '13 12:04 sq2

I think it should work like this.

sarunast avatar Apr 18 '13 12:04 sarunast

I think the docs should be updated. This has always been how this method has worked, including in L3.

Kindari avatar Apr 18 '13 21:04 Kindari

In the example you give you're not using an Eloquent object so it won't assume the table will have an id column, I think it's expected here.

When you would have used $user->roles()->lists('title') it's a different story, in that case I agree with you. I just looked at the source and it does not work like you expect, the key name is not used when no column was provided.

JoostK avatar Apr 18 '13 21:04 JoostK

@Kindari Just thought one or the other needed changing. I kind of like having the standard array option, too.

@JoostK Sorry, I should have said Query Builder instead of Eloquent. I'm using Eloquent just about everywhere except for this one line in a static function.

sq2 avatar Apr 18 '13 22:04 sq2

Yes, and what I'm saying is that the Query Builder is not aware of the primary key so it can't assume it simply is id, only Eloquent knows about this.

JoostK avatar Apr 18 '13 22:04 JoostK

Good point. So the docs are the issue. As minor as it is.

sq2 avatar Apr 18 '13 22:04 sq2

So it did in fact key by ID in L3? This could just be a bug in L4.

taylorotwell avatar Apr 19 '13 13:04 taylorotwell

It did not, only if you supplied the second argument. From what I can tell this functions exactly as it did in L3 - The documentation is just slightly misleading.

Kindari avatar Apr 19 '13 18:04 Kindari

Not sure about how L3 handled things. Only played with it for a short time before the L4 alpha release. You know how it goes, it's like crack. I might have a problem.

sq2 avatar Apr 19 '13 23:04 sq2