I'll-Be-Back I'll-Be-Back - 1 month ago 7
PHP Question

Search in other table?

I have a

maintenance
table with the following fields:
id
,
car_id
,
type
, and
name
.

How do I get list of entries from
maintenance
table where
type = 'car wash'
but only with
model_id = 5
?

model_id
field are in the
car
table. Car table with the following fields:
id
,
model_id
,
engine_size
, and
color
.

How can I use
Maintenance::where
to get list of entries with matching
model_id
in a
car
table? There is
car_id
in a
maintenance
table which link with
car
table.

Do I need to do something like this: ?

return Maintenance::where('type', 'car_wash')->where(function($query) {
// get a list a maintenance where model_id = 5 in a car table
});

Answer

Assuming you've already defined cars() relation on your Maintenance model you could try something like that:

$model_id = 5;
$type = 'car_wash';
return Maintenance::whereHas('cars',function($query) use($model_id,$type) {
  $query->where('model_id',$model_id)->where('type',$type);
  })->get();

Update for further question (skip if $model_id = 0):

 return Maintenance::whereHas('cars',function($query) use($model_id,$type) {
      if($model_id!=0){
          $query->where('model_id',$model_id);
      }
      $query->where('type',$type);
      })->get();

I did not tested it but it should work, otherwise let me know