【问题标题】:Getting Records with multiple ids in eloquent在 eloquent 中获取具有多个 id 的记录
【发布时间】:2015-12-16 12:08:55
【问题描述】:

您好,我将几件商品的 ID 及其数量发布到我的服务器,例如:

[{"id": "1", "quantity": "2"}, {"id": "2", "quantity": "5"}, {"id": "3", "quanity": "10"}]

现在在我的服务器上,我需要验证每个 ID,并从我的数据库表中它们各自的行中获取某些值。

我只想做的是:

foreach ($items as $item)
{
  $row = Items::find($item);
  $price = $row->price;
}

但在这里我想知道 foreach 循环是否会对速度性能产生巨大影响,因为项目可能很多。

我的问题是,有没有一种方法可以在 laravel 中执行此操作,而无需使用 foreach、循环,例如可以基于 id 数组获取数据的查询。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    如果你想获取某些id的所有价格属性,你可以使用查询的构建器whereIn方法来实现这一点。whereIn接受一个值数组并返回这些值对应的行。这也很划算在性能方面

    我看到你正在传递一个 json 字符串,所以如果你在哪里使用 whereIn 一个解决方案可能如下所示:

    示例

    //json string
    $json = '[{"id": "1", "quantity": "2"}, {"id": "2", "quantity": "5"}, {"id": "3", "quanity": "10"}]';
    
    //convert json to array
    $json_toArray = json_decode($json,true);
    
    //get id values from array
    //If you are using php 5.5+ this will work, if you are using an older version you can use 
    //array_map method like this: $array_ids = array_map(function ($array) {return $array['id'];}, $json_toArray);
    $array_ids = array_column($json_toArray, 'id');
    
    //Finally execute the query
    
    //Using Eloquent
    $result = Items::whereIn('id', $array_ids)->select('price')->get();
    
    //Using the Query Builder
    $result = DB::table('items')->whereIn('id',$array_ids)->select('price')->get();
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      相关资源
      最近更新 更多