使用从日期和日期过滤记录

时间:2017-08-30 12:31:21

标签: mysql laravel laravel-5 laravel-5.2 laravel-5.3

在我的情况下,我必须使用from-date和to-date

来过滤记录

我已经厌倦了介于两者之间但是只有当我同时输入日期和迄今

时它才有效
public function searchCustomers(Request $request, CustomerProfile $user)
{
    $fromDate = $request->get('from_date');
    $toDate = $request->get('to_date');
    $user = $user->newQuery();

    if ($request->has('city')) {
        $user->where('city', $request->input('city'));
    }

    if ($request->has('from_date') && $request->has('to_date')) {
        $user->whereBetween('date_of_visit', [$fromDate, $toDate]);
    }
    $results = $user->get();

    return response()->json($results);
}

但有时候我只是想只从日期开始搜索,有时我想只搜索至今,有时候我想用日期和迄今为止进行搜索,

如何获得以上输出?

5 个答案:

答案 0 :(得分:1)

if (isset($fromDate) && isset($toDate)) {
    $user->whereBetween('date_of_visit', array($fromDate, $toDate));
} else if (isset($fromDate)) {
    $user->where('date_of_visit', '>=', $fromDate);
} else if (isset($toDate)) {
    $user->where('date_of_visit', '<=', $toDate);
}

答案 1 :(得分:0)

您需要添加更多逻辑。我假设您只想搜索可用的逻辑。

if ($fromDate && $toDate) {
    $user->whereBetween('date_of_visit', [$fromDate, $toDate]);
} else if ($fromDate) {
    $user->where('date_of_visit', '>=', $fromDate);
} else if ($toDate) {
    $user->where('date_of_visit', '<=', $toDate);
}

答案 2 :(得分:0)

%timeit np.core.char.add('t', np.arange(1,100000).astype(str))
# 10 loops, best of 3: 31.7 ms per loop

f = lambda x: 't' + str(x)
%timeit list(map(f, np.arange(1,100000).astype(str)))
# 10 loops, best of 3: 38.8 ms per loop

答案 3 :(得分:0)

试试这个

public function searchCustomers(Request $request, CustomerProfile $user)
{
    $user = $user->newQuery();

    if ($request->has('city')) {
        $user->where('city', $request->input('city'));
    }

    if ($request->has('from_date')) {
        $user->where('date_of_visit', '>=', $request->get('from_date'));
    }

    if ($request->has('to_date')) {
        $user->where('date_of_visit', '<=', $request->get('to_date'));
    }

    $results = $user->get();

    return response()->json($results);
}

答案 4 :(得分:0)

你应该试试这个:

public function searchCustomers(Request $request, CustomerProfile $user)
{
    $fromDate = $request->get('from_date');
    $toDate = $request->get('to_date');
    $user = $user->newQuery();

    if ($request->has('city')) {
        $user->where('city', $request->input('city'));
    }

    if (!empty($fromDate) && !empty($toDate)) {
        $user->whereBetween('date_of_visit', [$fromDate, $toDate]);
    } else if(!empty($fromDate)){
        $user->where('date_of_visit', '>=', $fromDate);
    } else {
        $user->where('date_of_visit', '<=', $toDate);
    }
    $results = $user->get();

    return response()->json($results);
}