0

I'm trying to optimize a relationship using eager loading and implement conditions in the with clause for eager loading, however when I do the below:

 $totalOpenQry =  Enquiry::whereIn('staff_id', $employeeIds)
            ->with(['enquiryStats' => function ($query) {
                $query->where('is_open','=',true)
                    ->where('is_dead','=',false)
                    ->orderBy('id','asc');
            }])
            ->where('ed_timestamp', '>=', $dateRange['start'])
            ->with('country');

        $totalOpen = $totalOpenQry->toSql();

$totalOpenQry->toSql()

produces the following:

'select * from `enquiries` where `staff_id` in (10, 15) and `ed_timestamp` >= '2017-09-12';

It seems to be ignoring the where conditionals in my with clause. Is there a way to fix this or implement it properly?

Thanks

liamjnorman
  • 784
  • 1
  • 16
  • 30

2 Answers2

2

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

$totalOpenQry =  Enquiry::whereIn('staff_id', $employeeIds)
        ->with('enquiryStats')
        ->whereHas('enquiryStats', function ($query) {
            $query->where('is_open','=',true)
                ->where('is_dead','=',false)
                ->orderBy('id','asc');
        })
        ->where('ed_timestamp', '>=', $dateRange['start'])
        ->with('country');
// only  enquiryStats that have is_open = true and is_dead = false are returned
Mr. Pyramid
  • 3,855
  • 5
  • 32
  • 56
1

You'll get 2 query:

1: 'select * from `enquiries` where `staff_id` in (10, 15) and `ed_timestamp` >= '2017-09-12';

2 Something like: 'select * from `stats` where `staff_id` in (10, 15) AND `is_open`=true...;

But ->toSql() show first only.

aleksejjj
  • 1,715
  • 10
  • 21