1

$pidArray 包含产品 ID,其中一些产品 ID 可以相同。IE: 34 34 56 77 99 34. 看起来 whereIn 方法不会返回它已经在 $pidArray 中找到的 productId 的结果,即使它有不同的索引。

 $productDataForOrder = Product::whereIn('id', $pidArray)->get(['id','price']);


 $totalAmount = $productDataForOrder->sum('price');

$productDataForOrder 现在包含产品数据,但仅适用于 $pidarray 中的唯一 ProductID。因此,当 sum 函数运行时,sum 是错误的,因为它没有考虑相同 productID 的多个实例的价格。

以下代码也不会为数组中的每个产品 ID 返回相同的对象。因此,如果 $pidArray 包含三个相同的产品 ID,则查询将只返回一个包含一个对象的集合,而不是三个。

   $query = Product::select();
        foreach ($pidArray as $id)
        {
            $query->orWhere('id', '=', $id);
        }

        $productDataForOrder = $query->get(['id','price']);

        $totalAmount = $productDataForOrder->sum('price');
4

3 回答 3

2

您将无法以您尝试的方式获取重复数据。SQL 正在返回与您的 where 子句匹配的行。它不会仅仅因为您的 where 子句具有重复的 id 而返回重复的行。

这样想可能会有所帮助:

select * from products where id in (1, 1)

是相同的

select * from products where (id = 1) or (id = 1)

表中只有一条满足条件的记录,所以这就是你要得到的全部。

您将不得不在 PHP 中进行一些额外的处理才能获得您的价格。您可以执行以下操作:

// First, get the prices. Then, loop over the ids and total up the
// prices for each id.

// lists returns a Collection of key => value pairs.
// First parameter (price) is the value.
// Second parameter (id) is the key.
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');

// I used array_walk, but you could use a plain foreach instead.
// Or, if $pidArray is actually a Collection, you could use
// $pidArray->each(function ...)
$total = 0;
array_walk($pidArray, function($value) use (&$total, $prices) {
    $total += $prices->get($value, 0);
});

echo $total;
于 2016-04-11T06:29:37.883 回答
0

whereIn 方法仅将结果限制为给定数组中的值。从文档:

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

Id 创建一个查询变量并循环遍历数组,并在每次传递中添加到查询变量。像这样的东西:

$query = Product::select();

foreach ($pidArray as $id)
{
    $query->where('id', '=', $id);
}

$query->get(['id','price']);
于 2016-04-10T05:19:20.867 回答
0

这是一个适用于您在@patricus 上扩展的用例的代码您首先从 products 表中获取一个键数组作为 id 和值作为价格

$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');

$totalPrice = collect([$pidArray])->reduce(function($result, $id) use ($prices) {

      return $result += $prices[$id];

}, 0);
于 2016-08-03T14:15:17.887 回答