I have a filter that gets passed with the ajax.data property and in my controller
$model = Timesheet::select('*')->with(['user', 'job']);
return DataTables::of($model)
...
->filter(function ($query) {
if (request()->has('jobFilter') && !empty(request()->jobFilter)) {
$query->join('jobs', 'timesheets.job_id', '=', 'jobs.id');
$query->where('jobs.id', request('jobFilter'));
}
}, true)
->make(true);
Which works, but is there a way to just filter on the relationship without doing a join here?
Try using whereHas.
That's no help really. whereHas just returns records where the relationship exists but I need to filter based on properties of the relationship.
How did you do it? I think it something like below may work:
$model = Timesheet::select('*')->with(['user', 'job']);
return DataTables::of($model)
...
->filter(function ($query) {
if (request()->has('jobFilter') && !empty(request()->jobFilter)) {
$query->whereHas('job', function($query) {
$query->where('jobs.id', request('jobFilter'));
}
}
}, true)
->make(true);
Or you can have a hidden column for job.id for it to be included on search.
```js
columns: [
...,
{name: 'job.id', visible: false}
]
Oh yeah, whereHas with a callback. Dunno why that didn't register in my brain lol. It's right there in the docs too that you linked to. Sometimes you just can't see the wood for the trees.
Works great thanks!
Most helpful comment
How did you do it? I think it something like below may work: