Laravel - 使用Eloquent选择开始日期和结束日期之间的行

7

我想把这个查询转换成Laravel Eloquent语句:

select * from schedule where (now() between start_date and end_date);

我尝试使用whereBetween,但是遇到了一些错误。

$schedule = Schedule::whereBetween(Carbon::now(), ['start_date', 'end_date'])->get();

错误信息如下:
QueryException in Connection.php line 647: SQLSTATE[42S22]: Column not found: 1054 Unknown column '2017-06-01 06:17:30' in 'where clause' (SQL: select * from schedule where 2017-06-01 06:17:30 between start_date and end_date)
你有什么想法吗?
该错误是由于在 SQL 查询中使用了一个未知的列名“2017-06-01 06:17:30”,导致查询失败。可能需要检查列名是否正确,或者检查数据表中是否存在该列。

whereBetween 的第一个参数应该是列名,而不是值。 - Jerodev
5个回答

18
$from = $request->from;
$to = $request->to;
$title="Sales From: ".$from." To: ".$to;
$sales = Sale::whereBetween('created_at', [$from.' 00:00:00',$to.' 23:59:59'])->get();

8
$schedule = Schedule::where('start_date', '<=', Carbon::now())
    ->where('end_date', '>=', Carbon::now())
    ->get();

或者

$schedule = Schedule::whereRaw('(now() between start_date and end_date)')->get();

你能帮我解决我的问题吗?我有两列数据,start_at和end_at,需要在这两个日期之间获取数据,但是我还有两个日期需要检查,我不会使用now()进行检查。我有两个新的日期start_at和end_at。 - Mudit Gulgulia

6

当您想要查找单个列在两个值之间的行时,仅使用whereBetween。您要做的是:

$now = Carbon::now();
$schedule = Schedule::where('start_date', '<=', $now)
    ->where('end_date', '>=', $now)
    ->get();

2

如何正确使用whereBetween应该像这样->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172)) 其中第一个参数是列名,第二个参数是区域。

在您的情况下,您可以使用->where('start_date', '<', Carbon::now())->where('end_date', '>', Carbon::now());


你能帮我解决我的问题吗?我有两列数据,start_at和end_at,需要在这两个日期之间获取数据,但是我还有两个日期需要检查,我不会使用now()进行检查。我有两个新的日期start_at和end_at。 - Mudit Gulgulia
你可以使用我回答中的第二种方法,并将 Carbon::now() 更改为你的时间。 - LF00

0
你可以使用whereBetween('date_field',[$from_date, $to_date])来获取两个日期之间的数据,但是它应该是以数组格式提供。
$products = Sale::with('products')
    ->whereBetween('date',[$from_date, $to_date])
    ->get();
return response()->json($products);

您还可以使用whereBetween(whereBetween('date_field',[$from_date, $to_date]))与多个where条件一起使用,例如:

$products = Sale::with('products')
    ->whereBetween('date',[$from_date, $to_date])
    ->where(function ($query) use ($search) {
    $query->where('employee_id', 'like', '%'.$search.'%')
          ->orWhere('employee_name', 'like', '%'.$search.'%');
    })
    ->get();
return response()->json($products);

我希望这对你有用 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接