Fun
Fun

Reputation: 39

How to SUM a field inside of with eloquent relationships by using Laravel eloquent query format

$data = Product::with('items')->whereBetween('date', ['2000-01-01', '2000-01-31'])->get();
dump($data);

output

    [
      0=>[
        "id"=>11
        "type"=>"food"
        "items"=>[
          0 =>[
            "id"=>333
            "set_id"=>1
            "member_price"=> 22
            "non_member_price"=> 0
          ]
          1 =>[
            "id"=>444
            "set_id"=>2
            "member_price"=> 0
            "non_member_price"=> 33
          ] 
        ]
      ]
      1=>[
        "id"=>22
        "type"=>"food"
        "items"=>[
          0 =>[
            "id"=>444
            "set_id"=>1
            "member_price"=> 44
            "non_member_price"=> 0
          ]
          1 =>[
            "id"=>555
            "set_id"=>2
            "member_price"=> 0
            "non_member_price"=> 55
          ] 
        ]
      ]
      2=>[
        "id"=>33
        "type"=>"beverage"
        "items"=>[
          0 =>[
            "id"=>666
            "set_id"=>1
            "member_price"=> 66
            "non_member_price"=> 0
          ]
          1 =>[
            "id"=>777
            "set_id"=>2
            "member_price"=> 0
            "non_member_price"=> 77
          ] 
        ]
      ]
    ]

My question: How to SUM the fields member_price and non_member_price inside the relationship table of items when the type is same and also the set_id is same by using Laravel eloquent query?

I hope to get the result response like below

    [
      0=>[
        "id"=>11
        "type"=>"food"
        "items"=>[
          0 =>[
            "id"=>333
            "set_id"=>1
            "member_price"=> 66
            "non_member_price"=> 0
          ]
          1 =>[
            "id"=>444
            "set_id"=>2
            "member_price"=> 0
            "non_member_price"=> 88
          ] 
        ]
      ]
      1=>[
        "id"=>33
        "type"=>"beverage"
        "items"=>[
          0 =>[
            "id"=>666
            "set_id"=>1
            "member_price"=> 66
            "non_member_price"=> 0
          ]
          1 =>[
            "id"=>777
            "set_id"=>2
            "member_price"=> 0
            "non_member_price"=> 77
          ] 
        ]
      ]
    ]

Upvotes: 0

Views: 56

Answers (1)

shaedrich
shaedrich

Reputation: 5715

What about this?

$data = Product::with('items')
    ->withSum([ 'items.member_price', 'items.non_member_price' ])
    ->whereBetween('date', ['2000-01-01', '2000-01-31'])
    ->get();

Upvotes: 1

Related Questions