Laravel 5.3 WhereIn返回唯一结果 [英] Laravel 5.3 WhereIn returns unique result
本文介绍了Laravel 5.3 WhereIn返回唯一结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在其中whereIn遇到问题.我的代码看起来像这样
I'm having problem with this whereIn. My code looks like this
$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.该怎么做?我不知道
It only returns the unique id 1, 2, 4, 5. I need to return it 1, 2, 1, 4, 5, 1. How to do it? I don't have any idea.
推荐答案
这很正常,因为ID = 1
只有一行.如果出于某种原因您仍然想要获取具有[1, 2, 1, 4, 5, 1]
ID结构的集合,则需要使用collect()
和merge()
手动构建它:
It's normal, because there is only one row with ID = 1
. If for some reason you still want to get a collection with [1, 2, 1, 4, 5, 1]
IDs structure, you need to build it manually by using collect()
and 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);
我已经对其进行了测试,并且可以正常工作.
I've tested it and it works.
这篇关于Laravel 5.3 WhereIn返回唯一结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文