doutangtan6386
2018-02-05 04:22
浏览 123
已采纳

将集合的值转换为laravel中的键

this my mysql query:

$tmp=almacen::select('nombre_empresa','oferta')->join('users','users.id','=','almacen.emp_id')->where('almacen.event_id','5')->get();

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

$tmp['Aux2']
this return:
"Serv 12345678"

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

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

这是我的mysql查询:

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

这将返回以下几个对象:

  ... \  n App \ almacen {#1948 
 nombre_empresa:“Aux1”,
 oferta:“Serv_1234”,
},
 App \ almacen {#1947 
 nombre_empresa:“Aux2”,
 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

    https://laravel.com/docs/5.5/collections#method-mapwithkeys

    已采纳该答案
    打赏 评论
  • douyigua5381 2019-06-26 09:26

    You can use keyBy:

    $tmp->keyBy('nombre_empresa');
    

    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:

    $tmp=almacen::select('nombre_empresa','oferta')
        ->join('users','users.id','=','almacen.emp_id')
        ->where('almacen.event_id','5')
        ->pluck('oferta','nombre_empresa');
    

    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

    Example:

    $tmp=almacen::select('nombre_empresa','oferta')
        ->join('users','users.id','=','almacen.emp_id')
        ->where('almacen.event_id','5')
        ->get()
        ->pluck('oferta', 'nombre_empresa')
        ->toArray();
    

    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.
    打赏 评论

相关推荐 更多相似问题