I have a relation in Space model,
public function user()
{
return $this->belongsTo(User::class)->withTrashed();
}
In my controller, I want to search string from two columns 'first_name' & 'last_name' which are in 'users' table.
But I didn't find the syntax to write "or" conditon in whereRelation.
$query = new Space();
$query = $query->with('user')->whereRelation('user', 'first_name', 'like', '%' . $request->search . '%');
How to search the string in multiple columns of relational table using whereRelation?
Option 1. You can search from the two fields separately:
Space::with('user')->whereHas('user', function ($query) use ($request) {
$query->where('first_name', 'LIKE', '%' . $request->search . '%')
->orWhere('last_name', 'LIKE', '%' . $request->search . '%');
});
Option 2. What I'm guessing you really want is to join the two fields together with a space in between and compare your search to that:
use Illuminate\Support\Facades\DB;
// ...
Space::with('user')->whereHas('user', function ($query) use ($request) {
$query->where(
DB::raw('CONCAT(first_name, " ", last_name)'),
'LIKE',
'%' . $request->search . '%'
);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.