如何使用Eloquent模型过滤Laravel中的结果

时间:2017-11-29 19:57:32

标签: laravel laravel-5

我正在尝试使用以下

    $orders = \App\Order::with([
    'Customer' => function ($query) use ($filterFirst, $filterLast, $filterstate)
    {
        if($filterFirst)
        {
            $query->where('customers.first', 'LIKE', "{$filterFirst}%");
        }
        if($filterLast)
        {
            $query->where('customers.last', 'LIKE', "{$filterLast}%");
        }
        if ($filterstate)
        {
            $query->where('customers.state', '=', $filterstate);
        }
    },
    'Group' => function ($query) use ($filtercategory)
    {
        if($filtercategory)
        {
            $query->where('order_groups.groupid', '=', $filtercategory);
        }
    },
    'Group.ProductGroups' => function ($query) use ($filteractualcat)
    {
        if($filteractualcat)
        {
            $query->where('productgroups.cat', '=', $filteractualcat);
        }
    },
    'Group.ProductGroups.Category',
    'Doctor',
    'Status' => function ($query) use ($filterstatus)
    {
        if ($filterstatus)
        {
            $query->whereIn('statuses.id', $filterstatus);
        }
    },
    'Signed'
])->where(function ($query) use ($id, $filterlab, $filterStart, $filterEnd, $filterRep) {
    if ($id)
    {
        $query->where('orders.id', $id);
    }
    if ($filterlab)
    {
        $query->where('orders.labid', $filterlab);
    }
    if ($filterStart || $filterEnd)
    {
        if ($filterStart && $filterEnd)
        {
            $query->whereBetween('orders.created_at', [$filterStart, $filterEnd]);
        }
        else
        {
            if ($filterStart && !$filterEnd)
            {
                $query->where('orders.created_at', '>=', $filterStart);
            }
            else
            {
                $query->where('orders.created_at', '<=', $filterEnd);
            }
        }
    }
    if ($filterRep)
    {
        $query->where('salesrep', $filterRep);
    }
})->orderBy('orders.created_at', 'ASC');

但是,当我在->get上运行$orders时,我会获得整个订单表,而我只想获得与过滤器匹配的订单......

关于如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:1)

使用whereHas()按客户过滤条件过滤订单:

$orders = \App\Order::whereHas('Customer', function ($query) use ($filterFirst, $filterLast, $filterstate) {
        if ($filterFirst) {
            $query->where('first', 'like', $filterFirst . '%');
        }

        if ($filterLast) {
            $query->where('last', 'like', $filterLast . '%');
        }

        if ($filterstate) {
            $query->where('state', $filterstate);
        }
    })
    ->get();

如果您还想为订单加载客户,请在查询中添加with