我正在尝试创建过滤器,我只想使用一些条件将查询附加到关系。我不想将这些条件放在代码的第一 block 中。那么如何获取查询实例以便将新查询附加到现有关系中呢?
$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']);
}]);
}
目前,它只是覆盖第一个查询关系条件。
最佳答案
这应该有效:
$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']);
}
}]);
关于php - 如何将条件附加到 Eloquent 关系查询中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58552643/