一系列哈希laravel

时间:2017-12-10 12:21:59

标签: laravel laravel-4.2

使用Laravel 4.2 使用Eloquent查询检索以下数据结构。

[
  {
      Id: 1,
      Product:Test1,
      TypeId:100
   }
     {
      Id: 2,
      Product:Test2,
      TypeId:200
   }
      {
      Id: 3,
      Product:Test2,
      TypeId:200
   }
];

想要创建基于TypeId作为键的哈希映射,以便我可以轻松搜索产品。希望最终输出方式

{
      '100' :  {
          Id: 1,
          Product:Test1,
          TypeId:100
       },
       '200' : [

                     {
          Id: 2,
          Product:Test2,
          TypeId:200
       },
          {
          Id: 3,
          Product:Test2,
          TypeId:200
       }


       ]
}

尝试了以下雄辩的功能,但忽略了类型ID 200中的重复项 $ type_id_hash = $ FM-> fmmodelitems-> keyBy(' TYPEID&#39);

对于typeid 200,使用keyby函数时只存在一条记录,因为它忽略重复项。我想搜索hashmap数组以获取类似typeid的键。怎么做到呢。

1 个答案:

答案 0 :(得分:1)

也许你想要groupBy on Collection

$grouped = $fm->fmmodelitems->groupBy('TypeId');

这应该将它们分组在“密钥”下。

$collection = new Illuminate\Support\Collection([
    ['Id' => 1, 'Product' => 'Test1', 'TypeId' => 100],
    ['Id' => 2, 'Product' => 'Test2', 'TypeId' => 200],
    ['Id' => 3, 'Product' => 'Test3', 'TypeId' => 200]
]);

$grouped = $collection->groupBy('TypeId');

$grouped->all();

// array(
//   100 => array(
//     0 => array(
//       'Id' => 1,
//       'Product' => 'Test1',
//       'TypeId' => 100
//     )
//   ),
//   200 => array(
//     0 => array(
//       'Id' => 2,
//       'Product' => 'Test2',
//       'TypeId' => 200
//     ),
//     1 => array(
//       'Id' => 3,
//       'Product' => 'Test3',
//       'TypeId' => 200
//     )
//   )
// )