OrWhere does not work with Laravel eloquent relationship request

In Laravel, I have two tables called "Reservations and Clients." For a specific reservation, I have a relationship with one client. Everything works well when I request a customer for a reservation, unless I turn on orWhere. Please view the code snippet below.

if($client_name!=null) { $client_name='%'.$client_name; $bookings=$bookings->whereHas('client',function($q) use ($client_name){ $q->where('first_name','LIKE',$client_name) //->orWhere('last_name','LIKE',$client_name); }); } 

With the commented out line, orWhere I get the correct orders with the customer with first_name , as specified by the user. But when I use or in the query for last_name , all rows are displayed as if last_name matches every row.

What about him? Help me please.

+7
database php eloquent laravel-4
source share
1 answer

The problem is that you have code like this:

 WHERE foreignKey = X AND first_name = Y OR last_name = Z 

Thus, it is obvious that he is not returning what he needs.

Now, to make it work, you need to add these restrictions as a subdirectory, where:

 $bookings=$bookings->whereHas('client',function($q) use ($client_name){ $q->where( function ($q) use ($client_name) { $q->where('first_name','LIKE',$client_name) ->orWhere('last_name','LIKE',$client_name); }); }); 

This will result in a query like:

 WHERE foreignKey = X AND (first_name = Y OR last_name = Z) 

what you need.

+9
source share

All Articles