我在 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。该怎么做?我不知道。
最佳答案
这是正常的,因为只有一行ID = 1
。如果由于某种原因您仍然想获取具有 [1, 2, 1, 4, 5, 1]
ID 结构的集合,则需要使用 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);
我已经测试过它并且有效。
关于Laravel 5.3WhereIn 返回唯一结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40458146/