【问题标题】:Using array values to select database table in laravel在laravel中使用数组值选择数据库表
【发布时间】:2017-12-25 19:16:25
【问题描述】:

我有一个包含前 5 个产品的排序数组

foreach ($bestsellers as $item) {
      $data = json_decode($item->order_details, true);
      $product_ids[] = key($data);
}
      arsort($product_ids);
      $three = array_unique(array_slice($product_ids, 0, 5, true));
      print_r($three);

结果是

Array
(
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5
)

1,2,3,4,5 是产品 ID。是否可以在查询产品表中使用此值,以便我可以在页面上显示有关产品的更多信息。不仅仅是 ID。

有点像

Product::where('product_id', $value);

更新

$best = Product::whereIn('product_id', $three)->get();

foreach($best as $info)
{
    dd($info->title);
}

【问题讨论】:

    标签: arrays laravel laravel-4


    【解决方案1】:

    是的,您应该使用whereIn 作为数组。实际上,whereIn 将第二个参数作为指定列的值数组。

    Product::whereIn('product_id', $value);
    

    whereIn()

    whereIn 方法验证是否包含给定列的值 在给定的数组内:

    【讨论】:

    • 我需要添加循环来获取值还是可以像Product::whereIn('product_id', $product_ids);一样使用它?
    • 不需要循环,whereIn检查数组中的所有值
    • 我已经更新了我的问题。这仅返回一个结果。这是为什么呢?
    • @Ivan 你最后需要->get() 来获取id在给定数组中的产品详细信息
    • @Ivan 你不应该在 foreach 循环中使用 dd 它返回第一个
    猜你喜欢
    • 2018-07-31
    • 2020-11-08
    • 2015-02-20
    • 1970-01-01
    • 2020-12-18
    • 2018-02-06
    • 1970-01-01
    • 2019-10-14
    • 2018-08-17
    相关资源
    最近更新 更多