Home > Blockchain >  Laravel query builder when grouping
Laravel query builder when grouping

Time:09-27

I've started with Laravel for a week now and something bother me about the Query Builder and the when clause.

I'm using it like so:

$query->when($filters['full-time'] ?? false, fn ($query) =>
  $query->where('contract_type', JobPositionsEnum::class::FullTime)
);
      
$query->when($filters['location'] ?? false, fn ($query, $location) =>
  $query->where('location', 'like', '%' . $location . '%')
);

$query->when($filters['search'] ?? false, fn ($query, $params) => 
  $query->where('position', 'like', '%' . $params . '%')
    ->orWhere('description', 'like', '%' . $params . '%')
    ->orWhereHas('company', function ($query) use ($params) {
      $query->where('name', 'like', '%'.$params.'%');
    })
);

With this query I was hoping received an SQL request looking like this:

SELECT * FROM `jobs` 
WHERE `contract_type` = 'Full time' 
AND `location` like '%United%'
AND (`position` like '%S%' or `description` like '%S%' or EXISTS (SELECT * FROM `companies` WHERE `jobs`.`company_id` = `companies`.`id` and `name` like '%S%'))

But instead I'm receiving this:

SELECT * FROM `jobs` 
WHERE (
  `contract_type` = 'Full time' and 
  `location` like '%United%' and 
  `position` like '%S%' or `description` like '%S%' or EXISTS (
    SELECT * FROM 
      `companies` 
       WHERE `jobs`.`company_id` = `companies`.`id` 
       and `name` like '%S%'
   )
) 

I'm not sure to understand why the when group my query when I don't want to, did you know what I'm missing here ?

CodePudding user response:

You should use an additional where to group the or conditions.

Your last when should look like this:

$query->when($filters['search'] ?? false, function ($query) use ($params) {
    $query->where(function ($query) use ($params) {
        $query->where('position', 'like', '%' . $params . '%')
            ->orWhere('description', 'like', '%' . $params . '%')
            ->orWhereHas('company', function ($query) use ($params) {
                $query->where('name', 'like', '%' . $params . '%');
            });
    });
});
  • Related