Laravel eloquent Query Reuse extra condition

1.1k views Asked by At

I have a query which gives me list of total counts of different items, as:

$data = DB::table($Table1)
           ->join($table2,$Table1.'.id','=',$Table2.'.device_key')
                ->where($Table1.'.created_at', '>', $value)
                ->select('item', DB::raw('count(*) as total'))
                ->groupBy('item')
                ->lists('total', 'item');

now i want to fetch same data with extra condition as >where($Table1.'.status', '=', 'SUCCESS') .

how do i do that ??

2

There are 2 answers

1
Mārtiņš Briedis On

Use clone to copy the query object for modifications.

$query = DB::table()->where();

$clonedQuery = clone $query;
$clonedQuery->where(..);
0
DevK On

I don't think you'll get away with anything nice than this.

$query = DB::table($Table1)
           ->join($table2,$Table1.'.id','=',$Table2.'.device_key')
                ->where($Table1.'.created_at', '>', $value)
                ->select('item', DB::raw('count(*) as total'))
                ->groupBy('item');

$data1 = $query->lists('total', 'rem');
$data2 = $query->where($Table1 . '.status', '=', 'SUCCESS')->lists('total, 'rem');