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

jho*_*oss 3 php laravel laravel-5

这是我的 mysql 查询:

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

这将返回几个像这样的对象:

   ...
   App\almacen {#1948
     nombre_empresa: "Aux1",
     oferta: "Serv_1234",
   },
   App\almacen {#1947
     nombre_empresa: "Aux2",
     oferta: "Serv 12345678",
   },
  ...
Run Code Online (Sandbox Code Playgroud)

例如,我需要在一个键中转换“nombre_empresa”

$tmp['Aux2']
this return:
"Serv 12345678"
Run Code Online (Sandbox Code Playgroud)

可以在 Laravel 中做到这一点吗?还是我应该以另一种方式来做?

小智 9

当然 Laravel 可以处理,查看可用的集合方法mapWithKeys可能是你要找的:

$mapped = $results->mapWithKeys(function ($item) {
    return [$item['nombre_empresa'] => $item['oferta']];
});
Run Code Online (Sandbox Code Playgroud)

编辑:mapWithKeys而不是map

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


Dio*_*mes 9

您可以使用keyBy

$tmp->keyBy('nombre_empresa');
Run Code Online (Sandbox Code Playgroud)

您可以将其直接链接到查询末尾的 get 方法之后。

但在这种情况下,您只能从数据库中获取 2 个字段,您可以pluck直接在query builder使用:

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

pluck 的第二个参数将用作密钥。如果没有给出,它将只使用数字键:0、1、...