首页 > 解决方案 > 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();

标签: phplaravellumen

解决方案


它缺少对参数的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();

推荐阅读