2018-02-05 04:22
浏览 123


this my mysql query:


this returns several objects like these:

   App\almacen {#1948
     nombre_empresa: "Aux1",
     oferta: "Serv_1234",
   App\almacen {#1947
     nombre_empresa: "Aux2",
     oferta: "Serv 12345678",

i need to convert "nombre_empresa" in a key, for example

this return:
"Serv 12345678"

Is it possible to do this in Laravel? or should I do it in another way?

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


  $ tmp = almacen:  :选择( 'nombre_empresa', 'oferta') - >加入( '用户', '', '=', 'almacen.emp_id') - 化合物其中( 'almacen.event_id', '5'  ) - > get(); 


  ... \  n App \ almacen {#1948 
 App \ almacen {#1947 
 oferta:“Serv 12345678  “,

我需要在一个键中转换”nombre_empresa“,例如 < pre> $ tmp ['Aux2'] this返回: “Serv 12345678”

是否可以在Laravel中执行此操作? 或者我应该以另一种方式做到这一点?

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

3条回答 默认 最新

  • dongxun1142 2018-02-05 04:26

    Sure Laravel can handle that, check out the available collections methods. mapWithKeys is probably what you're looking for:

    $mapped = $results->mapWithKeys(function ($item) {
        return [$item['nombre_empresa'] => $item['oferta']];

    Edit: mapWithKeys rather than map

    打赏 评论
  • douyigua5381 2019-06-26 09:26

    You can use keyBy:


    You can chain it directly at the end of your query, after the get method.

    But on this case you are only getting 2 fields from the database you can use pluck directly on the query builder:


    The second argument of pluck will be use for the key. If none is given it will just use numeric keys: 0, 1,...

    打赏 评论
  • dragon7713 2019-07-10 07:23

    Of course, all solutions are valid, but the way I would do it which I think is also considered to be best practice in Laravel is by using pluck() Documentation


        ->pluck('oferta', 'nombre_empresa')

    Do notice that pluck() is a new method introduced in version 5.2 to replace the before used lists()

    • Notice that I would transform toArray() but it is not a must, I would consider it since with such a simple collection I might not need the extra functionality making this variable take up less space.
    打赏 评论

相关推荐 更多相似问题