簡體   English   中英

從Mysql Database Timestamp Laravel中僅選擇當前周的記錄

[英]Select only records of the current week from Mysql Database Timestamp Laravel

我想只獲得當周星期一到星期五的記錄,但是我很難思考和研究如何做到的方法,我在互聯網上找到了一些方法,但對新手來說很難理解像我一樣,所以這是我的代碼:

         $myquery=DB::table('attendances')
        ->leftJoin('employees', 'attendances.user_id', '=', 'employees.id')
        ->where('user_id', '=', $employee->id)

        //I want to do something like this one
         ->WHERE WEEK(`date`) = WEEK(NOW()  

        ->orderBy('attendances.date','asc')->get();

我實現了這樣的一些答案

         $myquery=DB::table('attendances')
        ->leftJoin('employees', 'attendances.user_id', '=', 'employees.id')
        ->where("WEEKOFYEAR(`date`)", "=", "WEEKOFYEAR(NOW())")
        ->where('user_id', '=', $employee->id)
        ->orderBy('attendances.logon','asc')->get();

您可以將whereBetween與兩個Carbon日期實例一起使用:

->whereBetween('date', [
    Carbon\Carbon::parse('last monday')->startOfDay(),
    Carbon\Carbon::parse('next friday')->endOfDay(),
])

如果要查找當月的所有記錄,請使用以下命令:

->whereBetween('date', [
    Carbon\Carbon::now()->startOfMonth(),
    Carbon\Carbon::now()->endOfMonth(),
])

您將需要使用WEEKOFYEAR()而不是WEEK ,它可以獲得一年中的當前周指數。 因此,同一周的兩個日期將返回相同的WEEKOFYEAR 在普通的SQL中,它看起來像:

... WHERE WEEKOFYEAR(`date`) = WEEKOFYEAR(NOW())

在laravel:

->where("WEEKOFYEAR(`date`)", "=", "WEEKOFYEAR(NOW())")

我會嘗試類似的東西

->where('WEEK(FROM_UNIXTIME(`date`))', '=', 'WEEK(NOW())') ->where('DAYOFWEEK(FROM_UNIXTIME(`date`))', '>=', 2) ->where('DAYOFWEEK(FROM_UNIXTIME(`date`))', '<=', 6)

要獲取當周的數據,不包括星期六和星期日:

$query->where(DB::Raw('week(date)'), '=', Carbon::now()->weekOfYear)
      ->where(function($query){
             return $query->where(DB::Raw('day(date)'),'<>',Carbon::SUNDAY)
                          ->orWhere(DB::Raw('day(date)'), '<>',Carbon::SATURDAY); });

那這個呢? (Eloquent / Laravel 5.6)

Model::whereMonth('created_at', '=', date('Y'));

它有很好的文檔記錄,效果很好: 查詢

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM