Reputation: 2277
I am trying to create the filters and I just want to attach the query to relation by using some conditionals. I don't want to put those conditional in the first block of the code. So how can I get the query instance so I can attach the new queries to the existing relation?
$query = Category::query();
$query->where('category_type', 'xyz')
->with(['products' => function ($query) {
$query->where('condition1', 'value')
->where('condition2', 'value');
}]);
if (isset($queryParams['param1'])) {
$query->with(['products' => function ($query) use ($queryParams) {
$query->getQuery()->where('type', $queryParams['param1']);
}]);
}
Currently, it just overwrites the first query relation condition.
Upvotes: 0
Views: 59
Reputation: 1295
This should work :
$query = Category::query();
$query->where('category_type', 'xyz')
->with(['products' => function ($query) use ($queryParams) {
$query->where('condition1', 'value')
->where('condition2', 'value');
if (isset($queryParams['param1'])) {
$query->where('type', $queryParams['param1']);
}
}]);
Upvotes: 1