【问题标题】:Left joining on a table, gets multiple records, reduce these 2 one ordered by smallest value左连接一个表,获取多条记录,减少这 2 个按最小值排序的记录
【发布时间】:2022-07-21 22:02:26
【问题描述】:

我正在做一个查询,其中列出了一些记录,我还加入了另一个表,由于加入的表中有多个行,结果返回了具有相同 ID 的多行:

array:35 [
  0 => array:3 [
    "id" => 1754853
    "monthly_payment" => "145.50"
    "regular_payment" => null
  ]
  1 => array:3 [
    "id" => 3006256
    "monthly_payment" => "272.81"
    "regular_payment" => null
  ]
  2 => array:3 [
    "id" => 3006257
    "monthly_payment" => "818.44"
    "regular_payment" => "90.37"
  ]
  3 => array:3 [
    "id" => 3006257
    "monthly_payment" => "818.44"
    "regular_payment" => "964.43"
  ]

如您所见,3006257 在数组中出现了两次。我现在需要使用 Laravel 的任何功能来操作这些数据,以将其减少到单个项目,但使用最低的 regular_payment。最好的方法是什么?

我选择进行左连接而不是附加查询,因为我只想进行单个查询。

查询

$vehicles = (clone $this->vehicles)
    ->select('id', 'monthly_payment', 'cache.regular_payment'))
    ->leftJoin('cache', 'cache.vehicle_id', '=', 'vehicles.id')
    ->get();

我尝试过 DB::raw('MIN(cache.regular_payment) as regular_payment')) 但这只是返回单行。

【问题讨论】:

  • 您能分享您的查询吗?
  • @Ludo.C 添加到帖子底部。

标签: php laravel


【解决方案1】:

设法用reduce 做我想做的事,可能不是最干净的代码,所以如果有人知道如何减少代码量或使其更干净,将不胜感激。

$vehicles = $vehicles->reduce(static function ($carry, $item) {
    /** @var $carry Collection */
    $monthly_payment = $item->getAttribute('monthly_payment');
    $id = $item->getAttribute('id');
    
    if ($regular = $item->getAttribute('regular_payment')) {
        if ($carry->has($id)) {
            $monthly_payment = $carry->get($id)['monthly_payment'];
            if ($regular < $carry->get($id)['monthly_payment']) {
                $monthly_payment = $regular;
            }
        }
        if (!$carry->has($id)) {
            $monthly_payment = $regular;
        }
    }
    return $carry->put($id, [
        'id' => $id,
        'monthly_payment' => $monthly_payment
    ]);
}, collect([]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多