【问题标题】:Laravel 5.3 WhereIn returns unique resultLaravel 5.3 WhereIn 返回唯一结果
【发布时间】:2016-11-07 05:02:22
【问题描述】:

我遇到了这个 whereIn 的问题。我的代码是这样的

 $arrayKeys = [1, 2, 1, 4, 5, 1];
    $products = \App\Product::whereIn('id', $arrayKeys)
                    ->select(['id', 'name', 'outright_price', 'discount', ])
                    ->with('photo', 'colors')
                    ->get();

它只返回唯一的id 1、2、4、5。我需要返回1、2、1、4、5、1。怎么做?我没有任何想法。

【问题讨论】:

  • 只返回 1,2,4,5 是什么意思?您的意思是记录 1、2、4 和 5?
  • 是的,来自数据库的记录。
  • 我得到了记录 id 1, 2, 4, 5 但我需要 1, 2, 1, 4, 5, 1 。我认为它不能通过 whereIn 来完成,但我怎样才能实现这些记录。谢谢。
  • 您可以使用循环遍历数组,甚至可以使用 Like 子句?

标签: laravel


【解决方案1】:

这很正常,因为ID = 1 只有一行。如果出于某种原因您仍想获得具有[1, 2, 1, 4, 5, 1] IDs 结构的集合,则需要使用collect()merge() 手动构建它:

$arrayKeys = [1, 2, 1, 4, 5, 1];

$products = collect([]);

$productData = \App\Product::whereIn('id', $arrayKeys)
        ->select(['id', 'name', 'outright_price', 'discount'])
        ->with('photo', 'colors')
        ->get();

foreach ($arrayKeys as $key) {
    $products = $products->merge($productData->where('id', $key));
}

dd($products);

我已经测试过了,它可以工作。

【讨论】:

  • 打败我!只是输入几乎相同的答案! +1
  • 谢谢,可以创建多个查询。
  • @Rbex,我找到了一种更好的方法,它不会创建多个类似的查询(好吧,由于急切加载,它将是 3 而不是第一个变体中的 18)。我已经更新了我的代码。在此代码中,您只查询一次以获取数据,然后从该数据手动创建新集合。
猜你喜欢
  • 2017-05-29
  • 1970-01-01
  • 2017-12-29
  • 2017-10-11
  • 2021-03-21
  • 1970-01-01
  • 2020-01-05
  • 2021-03-19
  • 2021-07-14
相关资源
最近更新 更多