Laravel合并以合并相同的ID

时间:2019-03-21 08:45:03

标签: laravel

您好,我的查询已经在工作,并且它结合了两个查询,但是我需要结合相同的"Resource": [ "arn:aws:amplify:us-east-1:26XXXXXXXXXX:apps/*", "arn:aws:amplify:us-east-1:26XXXXXXXXXX:*" ] 而不是将其输出到另一个数组中。

这是我的代码:

product _id

我的结果是:

$first = DB::table('delivery_receipt_detail');
$first->join('delivery_receipts', 'delivery_receipt_detail.delivery_receipt_id', '=', 'delivery_receipts.id');
$first->where(function ($first) use ($start_date, $end_date) {
    $first->whereBetween('delivery_receipts.posting_date', [new Carbon($start_date), new Carbon($end_date)]);
    $first->orWhereDate('delivery_receipts.posting_date', '=', new Carbon($start_date));
    $first->orWhereDate('delivery_receipts.posting_date', '=', new Carbon($end_date));
});
$first->groupBy('delivery_receipt_detail.product_id');
$first->select('delivery_receipt_detail.product_id as delivery_product_id', DB::raw('SUM(product_qty) as delivery_product_qty'));
$result_one = $first->get();

//Sales
$query = DB::table('sale_detail');
$query->join('sales', 'sale_detail.sale_id', '=', 'sales.id');
$query->where(function ($query) use ($start_date, $end_date) {
    $query->whereBetween('sales.posting_date', [new Carbon($start_date), new Carbon($end_date)]);
    $query->orWhereDate('sales.posting_date', '=', new Carbon($start_date));
    $query->orWhereDate('sales.posting_date', '=', new Carbon($end_date));
});

$query->groupBy('sale_detail.product_id');
$query->select('sale_detail.product_id as sales_product_id', DB::raw('SUM(product_qty) as sales_product_qty'));
$test = $query->get();

$merged = $result_one->merge($test);

$result = $merged->all();

return $result;

我需要的是这个输出

 [
    {
    "delivery_product_id": "1",
    "delivery_product_qty": 4
    },
    {
    "delivery_product_id": "2",
    "delivery_product_qty": 1
    },
    {
    "sales_product_id": "1",
    "sales_product_qty": "3"
    },
    {
    "sales_product_id": "2",
    "sales_product_qty": "3"
    }
 ]

我需要将其合并并合并相同的product_id并显示其不同数量。

1 个答案:

答案 0 :(得分:0)

对于这种情况,我认为您在选择时只需为product_id指定相同的名称,其余的->merge就可以

$first = DB::table('delivery_receipt_detail')
    ->select('delivery_product_id as product_id', 'delivery_product_qty');
// ...

$query = DB::table('sale_detail')
    ->select('sales_product_id as product_id', 'sales_product_qty');
// ...

$merged = $result_one->merge($test);