简体   繁体   English

Laravel 其中日期时间

[英]Laravel wherebetween datetime

I have a problem using wherebetween to filter data by timestamp (datetime)我在使用 wherebetween 按时间戳(日期时间)过滤数据时遇到问题

To test query, this is my route要测试查询,这是我的路线

Route::get('/test3/{iduser}/{waktu}', 'SharedController@fgetxy_person');

and this is URL test这是 URL 测试

http://localhost:8000/test3/32/2020-12-08 2010:15:00

this is my controller这是我的 controller

public function fgetxy_person($iduser, $waktu){
        $time = Carbon::createFromFormat('Y-m-d H:i:s', $waktu, 'Asia/Jakarta');
        // dd($time->addMinutes(-5)); //output: 10:10:00
        // dd($time->addMinutes(30)); //output: 10:45:00
        $xybeacon = DB::table('transaksi as tb')
        ->select('tb.id_ble', 'tb.rssi', 'tb.id_ble2', 'tb.rssi2', 'tb.id_ble3', 'tb.rssi3','tb.updated_at')
        ->where('id_user', $iduser)
        ->whereBetween('updated_at', [$time->addMinutes(-5), $time->addMinutes(30)])    //output: []
        // ->whereBetween('updated_at', array($time->addMinutes(-5), $time->addMinutes(30)))    // output: []
        // ->where('updated_at','>=',$time->addMinutes(-5))    //output: 94 array
        // ->where('updated_at','<=',$time->addMinutes(30)) //output: 35 array
        
        // ->whereRaw(
        //     "(updated_at >= ? AND updated_at <= ?)", 
        //     [$time, $time->addMinutes(30)]
        //   )  //output: []
        
        ->get();

The problem is, I cannot get data using wherebetween.问题是,我无法使用 wherebetween 获取数据。

If I try used 1 where, for example addMinutes(-5), I can get the data.如果我尝试使用 1,例如 addMinutes(-5),我可以获得数据。

but when used 2 where addMinutes(-5) and addMinutes(30), I get empty array []但是当在 addMinutes(-5) 和 addMinutes(30) 中使用 2 时,我得到空数组 []

Any help would be greatly appreciated任何帮助将不胜感激

The default carbon instances are mutable, meaning if you are using the same instance you will always be using the same time.默认的 carbon 实例是可变的,这意味着如果您使用相同的实例,您将始终使用相同的时间。 You should switch to immutable Carbon instances.您应该切换到不可变的 Carbon 实例。

public function fgetxy_person($iduser, $waktu){
        $time = CarbonImmutable::createFromFormat('Y-m-d H:i:s', $waktu, 'Asia/Jakarta');
        $xybeacon = DB::table('transaksi as tb')
        ->select('tb.id_ble', 'tb.rssi', 'tb.id_ble2', 'tb.rssi2', 'tb.id_ble3', 'tb.rssi3','tb.updated_at')
        ->where('id_user', $iduser)
        ->whereBetween('updated_at', [$time->addMinutes(-5), $time->addMinutes(30)])        
        ->get();

This will ensure that the two parameters in whereBetween refer to a different time.这将确保whereBetween中的两个参数引用不同的时间。

The difference is that all functions that change the time on the instance will return a new instance with that time instead of returning the same instance with the time changed.不同之处在于,所有更改实例时间的函数都将返回一个具有该时间的新实例,而不是返回具有更改时间的同一实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM