1

Laravel 8.x

I'm trying to do something like mentioned over here

(code copied from above link- minor change to comment)

$total = OrderTotals::whereIn('order_id', function($q) use($query) {
   // here would like to use the query of the parent instead of an empty fresh query
})->sum('value);

Where I would like to use the previous query in the subquery when calling ->whereIn is this possible how can I do this?

The $query variable in the closure is empty and produces a select * without any from or wheres. This make sense since a subquery can be wanted to be fresh. But what if I would like to use the existing query?

I used this google search among many others to find a similar question. The results on stackoverflow don't seem to use the existing query, they all add new froms and wheres (see here and this highly rated question).

shmuels
  • 1,039
  • 1
  • 9
  • 22
  • from what I understood you need the OrderTotals that their order_id is in [...] and u want to have the total of them if some condition is met . – Amir Daneshkar Jun 01 '21 at 18:40
  • I want where their order_id is in a subquery not and array. If I do whereIn and pass a closure then that's a subquery. The problem is that I want the subquery to be the parent query but a whereIn doesn't give you handle to the parent query only to a fresh query. – shmuels Jun 01 '21 at 19:16
  • i think my answer can help you, look at second part – Amir Daneshkar Jun 01 '21 at 19:20

1 Answers1

0

See if something like this helps

Model::where(function($query)
{
    $query->whereIn('order_id', [1,2,3]);

    //OR

    $query->or_where('order_id', function(){
         // do something
    });

})->where('other condition')->sum('value');

this may also work :

OrderTotals::addSelect(['order_id' => Order::select('id')
    ->whereColumn('active', 0)
    ->orderByDesc('completed_at')
])->sum();
Amir Daneshkar
  • 771
  • 3
  • 9