Php 通过Laravel中的路由查询参数动态查询数据库
我正在处理一个项目,我需要一个端点根据提供的不同路由参数返回不同的数据,例如:Php 通过Laravel中的路由查询参数动态查询数据库,php,laravel,lumen,Php,Laravel,Lumen,我正在处理一个项目,我需要一个端点根据提供的不同路由参数返回不同的数据,例如:api/v1/vendors?asset\u type=assetTypeId&get\u only\u vendors\u with_email=true应该给我提供assetTypeId的所有供应商以及有电子邮件地址的供应商。我怎样才能在拉威尔做到这一点 这就是我迄今为止所尝试的: $query = Vendor::query()->where('account_id', $accou
api/v1/vendors?asset\u type=assetTypeId&get\u only\u vendors\u with_email=true
应该给我提供assetTypeId的所有供应商以及有电子邮件地址的供应商。我怎样才能在拉威尔做到这一点
这就是我迄今为止所尝试的:
$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();
检查
资产类型参数时,缺少。添加以下内容:
$query->when(request('asset_type'), function ($q) {
return $q->where('asset_type', request('asset_type');
});
还有,如果你的第一句话是
$query=Vendor::query()->其中('account\u id',$accountID);
为什么在每次调用when
时都添加对account\u id
的where查询
您可以这样简化它:
$query=Vendor::query()->其中('account\u id',$accountID);
$query->when(请求('get\u only\u vendors\u with\u email',false),函数($q){
返回$q->whereNotNull(“电子邮件地址”);
});
$query->when(请求('get\u only\u maintenance\u vendors',false),函数($q){
返回$q->where('is_maintenance',request('get_only_maintenance_vendors');
});
$query->when(请求('get\u only\u purchase\u vendors',false),函数($q){
返回$q->where('is\u purchase',true);
});
$query->when(请求('get\u only\u maintenance\u vendors',false),函数($q){
返回$q->where('is_maintenance',request('get_only_maintenance_vendors');
});
$query->when(请求('asset_type')、函数($q){
返回$q->where('asset_type',request('asset_type');
});
$vendors=$query->get();
asset\u type在哪里?它应该来自url。类似这样:api/v1/vendors?asset\u type=2&get\u only\u vendors\u with\u email=true。您得到了吗?@Hamid Shariati您的问题不清楚。预期的输出是什么?尝试时,它返回了哪些与预期不同的数据?