duanfeiqu1989
2014-11-11 13:19
采纳率: 100%
浏览 1.4k
已采纳

Laravel Eloquent:返回数组键作为字段ID

当我通过Laravel's Eloquent ORM执行查询时,我希望获得行ID作为Array结果键,那么我在根据ID(使用Array_key_ITES)检查某项内容或执行一些查找(如果我需要从结果数组中指定一个条目)时会变得更容易。

能告诉我如何设置Eloquent字段ID吗?see image http://oi60.tinypic.com/kc02a8.jpg

图片转代码服务由CSDN问答提供 功能建议

当我通过Laravel的Eloquent ORM执行查询时,我想得到行ID作为数组结果键,这个 当我想根据ID(使用array_key_exists)检查某些内容或进行一些查找(如果我需要结果数组中的特定条目)时,会使事情变得更容易。

有没有办法 我可以告诉Eloquent将密钥设置为字段ID吗? 参见图片http://oi60.tinypic.com/kc02a8.jpg

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • dounai9592 2016-02-06 22:18
    已采纳

    You can simply do

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

    Cheers :)

    打赏 评论
  • duanlang1531 2014-12-01 17:52

    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.

    打赏 评论
  • dongmangji0950 2015-04-05 03:38

    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.

    打赏 评论
  • dt2015 2016-02-05 10:58

    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);
    
    打赏 评论
  • douduan9129 2019-08-20 04:36

    pluck('label','id') on the get() output is what you're looking for in Laravel 5.8+, which gives you a collection, ready to be toArray()ed

    eg:

    $options = \App\DataChoice::where([ 'field_id' => $dataField->id , 'active' => true ])->get()->pluck('label','id')->toArray();
    

    I had a similar challenge - I wanted to a PHP array to allow me to create a with an for each choice, with the 's value being the id auto increment column, and the displayed text being the value.

    打赏 评论

相关推荐 更多相似问题