php - Laravel中通过路由查询参数动态查询数据库
问题描述
我正在做一个项目,我需要一个端点来根据提供的不同路由参数返回不同的数据,例如:api/v1/vendors?asset_type=assetTypeId&get_only_vendors_with_email=true
应该给我所有提供了assetTypeID的供应商以及有电子邮件地址的供应商。我怎样才能在 Laravel 中实现这一点?
这是我到目前为止所尝试的:
$query = Vendor::query()->where('account_id', $accountID);
$query->when(request('get_only_vendors_with_email', false), function ($q, $accountID) {
return $q->whereNotNull('email_address')->where('account_id', $accountID);
});
$query->when(request('get_only_maintenance_vendors', false), function ($q, $accountID) {
return $q->where('is_maintenance', request('get_only_maintenance_vendors'))->where('account_id', $accountID);
});
$query->when(request('get_only_purchase_vendors', false), function ($q, $accountID) {
return $q->where('is_purchase', true)->where('account_id', $accountID);
});
$query->when(request('get_only_maintenance_vendors', false), function ($q, $accountID) {
return $q->where('is_maintenance', request('get_only_maintenance_vendors'))->where('account_id', $accountID);
});
$vendors = $vendorQuery->get();
解决方案
它缺少对参数的when
检查。asset_type
添加这个:
$query->when(request('asset_type'), function ($q) {
return $q->where('asset_type', request('asset_type');
});
此外,如果您的第一个陈述是
$query = Vendor::query()->where('account_id', $accountID);
为什么要account_id
在每次when
调用中添加 where 查询?
您可以像这样简化它:
$query = Vendor::query()->where('account_id', $accountID);
$query->when(request('get_only_vendors_with_email', false), function ($q) {
return $q->whereNotNull('email_address');
});
$query->when(request('get_only_maintenance_vendors', false), function ($q) {
return $q->where('is_maintenance', request('get_only_maintenance_vendors'));
});
$query->when(request('get_only_purchase_vendors', false), function ($q) {
return $q->where('is_purchase', true);
});
$query->when(request('get_only_maintenance_vendors', false), function ($q) {
return $q->where('is_maintenance', request('get_only_maintenance_vendors'));
});
$query->when(request('asset_type'), function ($q) {
return $q->where('asset_type', request('asset_type');
});
$vendors = $query->get();
推荐阅读
- selenium - 谷歌仍然支持硒测试谷歌地图吗?
- node.js - 我无法在 Angular7 中使用“ng new myworkspace”命令创建工作区。可能是什么原因
- php - Laravel 和 MySQL 按周获取数据
- apache - 403 Forbidden on CORS request from local
- wkhtmltopdf - 使用 wkhtmltopdf.exe 渲染丑陋的 Arial 字体
- kubernetes - 供应 IBM Cloud Kubernetes 服务所需的用户权限
- c++ - Windows:如何解决缺少的过程入口点以实现向后兼容性?
- model-view-controller - 模型视图... 适用于 Blazor
- c# - 页面不断加载,Google Calendar API
- c# - 如何在达到流畅的验证实现 C# 之前避免 MVC 验证引发的错误