I'm using using Spaties LaravelQueryBuilder to allow for some additional filtering on my api.
I've got a model called 'AvailableIntegration' and this model has a relationship through to Category that is a belongsToMany;
Without QueryBuilder I can make the following query
$availableIntegrations = QueryBuilder::for(AvailableIntegration::class)
->allowedIncludes(['categories'])
->with(['categories'])
->paginate();
and this returns
"data": [
{
"id": "2b3bf55a-b09f-61eb-c86b-0f749868b2df",
"name": "Product Name",
"categories": [
{
"id": "8b3bf55a-b09f-61eb-ca09-c2a671d29bbb",
"name": "Payments"
}
]
}
],
What I would like to do is to filter this by category.
So far, I've managed to filter by category_id by using ->join to attach the related table
eg:
/integrations?filter[categories]=8b3bf55a-b09f-61eb-ca09-c2a671d29bbb
using:
$availableIntegrations = QueryBuilder::for(AvailableIntegration::class)
->join('available_integration_category',
'available_integrations.id',
'available_integration_category.available_integration_id')
->allowedFilters(
AllowedFilter::exact('categories', 'available_integration_category.category_id', false)
)
->allowedIncludes(['categories'])
->with(['categories'])
->paginate();
returns
"data": [
{
"id": "8b3bf55a-b09f-61eb-ca09-c2a94268a229",
"name": "Product Name",
"categories": []
}
],
Whilst this does apply the filter and get me the correct result filtered by 'available_integration_category.category_id', what is happening is that I'm loosing the results that were coming through:
"categories": []
I've been reading https://spatie.be/docs/laravel-query-builder/v3/features/filtering but not able to spot what I need (apart from whether I should be adding scopes)
So my question is two fold.
- 1: can anyone advise on the correct way to filter on belongsToMany
- 2: does anyone know why my 'categories' aren't being returned when I add the join?
Thanks in advance.