简体   繁体   中英

Cakephp MYSQL query: SELECT where date is greater than

I have to run a MYSQL select query where the query returns all values that have the beginning date 10 days after today. I have tried these two methods none of which seem to work, where do I need to make a change?

$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(['month(date_from)' => 03])
    ->andWhere(['date_from' >= date("Y-m-d",strtotime("+10 days"))])
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(['month(date_from)' => 03])
    ->andWhere(['date(date_from)' >= date("Y-m-d",strtotime("+10 days"))])
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

Try below one

$fix_d_table = TableRegistry::get('fixed_departures'); $f_dates_march
= $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(
        function ($exp) {
            return $exp->or_([
                'date_from <=' => date('Y-m-d', strtotime("+10 days")),
                'date_from >=' => date('Y-m-d')
            ]);
    })
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

should be

'date_from >=' => date("Y-m-d",strtotime("+10 days"))

if you can rely on mysql server date you can use NOW() inside your query

 ->where(function($exp, $q) {
        return $exp->gte($q->func()->dateDiff([
            'date_from ' => 'identifier',
            $q->func()->now() ]),  10);
    });

this will give you the following SQL condition

WHERE 
(
  DATEDIFF(date_from , NOW())
)  >= 10 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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