programing

날짜 사이의 Laravel $q->where()

minimums 2023. 9. 5. 20:04
반응형

날짜 사이의 Laravel $q->where()

나는 내 크론이 오직 얻도록 노력하고 있습니다.Projects알림 이메일을 발송하기 위해 향후 7일 이내에 재발/재발될 예정입니다.저는 제 논리가 제대로 작동하지 않는다는 것을 방금 알았습니다.

현재 질문이 있습니다.

$projects = Project::where(function($q){
    $q->where('recur_at', '>', date("Y-m-d H:i:s", time() - 604800));
    $q->where('status', '<', 5);
    $q->where('recur_cancelled', '=', 0);
});

하지만 제가 해야 할 일은 다음과 같은 것이라는 것을 깨달았습니다.

Psudo SQL:

SELECT * FROM projects WHERE recur_at > recur_at - '7 days' AND /* Other status + recurr_cancelled stuff) */

Laravel 4에서는 어떻게 해야 할까요? DATTIME 데이터 유형을 사용하여 타임스탬프를 사용하여 이러한 작업을 수행했습니다.

업데이트:

다음 코드를 사용한 후 이 문제를 해결할 수 있는 스택 오버플로는 코드 조각을 당겨서 컨텍스트 밖으로 볼 수 있는 경우에도 도움이 됩니다.

$projects = Project::where(function($q){
    $q->where(DB::raw('recur_at BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()'));
    $q->where('status', '<', 5);
    $q->where('recur_cancelled', '=', 0);
});

업데이트된 질문:Laravel/Eloquent에서 이것을 하는 더 좋은 방법이 있습니까?

업데이트 2:

추가 테스트 후 첫 번째 해결책이 제대로 나오지 않았습니다. 이제 다음 솔루션을 해결하고 테스트했습니다.

$projects = Project::where(function($q){
    $q->where('recur_at', '<=', Carbon::now()->addWeek());
    $q->where('recur_at', '!=', "0000-00-00 00:00:00");
    $q->where('status', '<', 5);
    $q->where('recur_cancelled', '=', 0);
});

체인으로 연결할 수 있습니다.wheres 직접, 없이function(q)카본이라고 불리는 라벨로 된 멋진 데이트 상대 패키지도 있습니다.따라서 다음과 같은 작업을 수행할 수 있습니다.

$projects = Project::where('recur_at', '>', Carbon::now())
    ->where('recur_at', '<', Carbon::now()->addWeek())
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

Carbon in Composer가 필요하고 Carbon 네임스페이스(Carbon\Carbon; 사용)를 사용하면 작동합니다.

편집: Joel이 말했듯이 다음과 같은 작업을 수행할 수 있습니다.

$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

탄소를 건드리고 싶지 않았습니다.그래서 제 해결책은 이렇습니다.

$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');

$new_releases = Game::whereBetween('release', array($start, $end))->get();

@Tom : '지금'이나 '추가'를 사용하는 대신Week' 날짜를 다음 형식으로 제공하면 정확한 기록이 제공되지 않습니다.

$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();

2015-10-16에서 2015-10-23 미만의 날짜를 가진 기록을 제공합니다.recur_at의 값이 2015-10-23 00:00:00이면 레코드만 표시됩니다. 그렇지 않으면 2015-10-23 12:00:45이면 레코드가 표시되지 않습니다.

편집됨: 참고:
whereBetween('date',$start_date,$end_date)
첫 번째 날짜를 포함합니다.

언급URL : https://stackoverflow.com/questions/24824624/laravel-q-where-between-dates

반응형