When I execute a query via Laravel's Eloquent ORM, I want to get the row ID as the Array result key, this will make things easier when I want to check something based on an ID (using array_key_exists) or do some look ups (if I need a specific entry from the result array)

Is there any way I can tell Eloquent to set the key to the fields ID? see image http://oi60.tinypic.com/kc02a8.jpg

 
   
loop the results and create a new array? – itachi Nov 11 '14 at 13:22
   
Thought about it, but I figured there should be a way to do it through eloquent... :-/ – Broshi Nov 11 '14 at 14:37
   
I have to agree you would have to do it yourself. Alternatively you could use ->find($id) on the collection to find a model by id... – lukasgeiter Nov 11 '14 at 15:35
   
You have plenty of methods: laravel.com/api/4.2/Illuminate/Support/Collection.html & laravel.com/api/4.2/Illuminate/Database/Eloquent/… so you shouldn't need to do it. Eloquent doesn't provide such thing. – Jarek Tkaczyk Nov 12 '14 at 12:15

4 Answers 正确答案

You can simply do

    Model::all()->keyBy('category_id');

Cheers :)

 

Since you have an Eloquent Collection (a child class of the generic Collection class) you can use the getDictionary method$collection->getDictionary() will give you an array of your Category objects keyed by their primary keys.

If you wanted another Collection rather than a native PHP array, you could instead use $collection->keyBy($property). It looks like your primary key is category_id, so $collection->keyBy('category_id'). You can use that method to key by any arbitrary property, including any get mutators you may have written.

While getDictionary is unique to the Eloquent Collection extension, keyBy is available to all Laravel Collection objects. See the Laravel 4.2 API docs or Laravel 5.0 API docs.

 

You have a Support\Collection/Database\Eloquent\Collection you can use the method lists('id') to return an array of the id of each of the models within the collection.

Then use array_combine to map the keys to the models. The result of which will be an array with the id mapped to their corresponding model.

 

If you need id as the key, then rely on the Collection:

$collection = Model::all();

$collection->getDictionary();

// returns:
array(
  1 => object(Model) ( ... ),
  2 => object(Model) ( ... ),
  ...
  idN => object(Model) ( ... )
);

Otherwise, nice or not, you can do this:

$keys = $collection->lists('columnName');

$arrayOfModels = array_combine($keys, $collection->getDictionary);
 

来自  https://stackoverflow.com/questions/26865877/laravel-eloquent-return-array-key-as-the-fields-id