-1

Just as title say, i want to query query relationships(plural). I saw numerous examples such as this

which work well. But it's querying only one relationship.

Can it just:

Vehicle::with("deliveries", "user", "type", "workOrganization")->get();

go like this:

Vehicle::with("deliveries", "1", "user", "1", "type", "1", "workOrganization", "1")->get();

where number "1" is an id. Or are those two ways for this, are only ways to approach this?

And i want to say, any of these ids are optional, so that even muddies the water even further...

1 Answers1

1

You can but you have to split them like:

Vehicle::whereHas('deliveries', function (Builder $query) {
     $query->where('deliveries.id', '=', '1');
})->get();

And so on and so forth. Just giving you the first example to get an idea of how to approach it.

If it's optional then you can use a when clause passing a variable and check it like this in your query before you use a relationship so something like:

$deliveriedId = null;

    Vehicle::when(!empty($deliverieId), function ($q) {
          return $q->whereHas('deliveries', function (Builder $query) {
              $query->where('deliveries.id', '=', '1');
          })
       });

Basically the above code will check if your variable is not empty and then and only then will use the relationship deliveries to filter out your results. This normally comes from the request.

So that way you make it optional when to use and not not like you stated in your question.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36