【问题标题】:Cakephp MYSQL query: SELECT where date is greater thanCakephp MYSQL查询:选择日期大于
【发布时间】:2018-03-23 05:55:20
【问题描述】:

我必须运行MYSQL 选择查询,其中查询返回开始日期为今天之后 10 天的所有值。这两种方法我都试过了,似乎都不起作用,我需要在哪里进行更改?

$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();

【问题讨论】:

  • 我很想在原始 MySQL 中找到一个有效的查询,并重新设计它以适合您的框架

标签: php mysql sql datetime cakephp


【解决方案1】:

试试下面一个

$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();

【讨论】:

    【解决方案2】:

    应该是

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

    如果您可以依赖 mysql 服务器日期,您可以在查询中使用 NOW()

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

    这将为您提供以下 SQL 条件

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

    【讨论】:

    • 我曾经在我的查询中有 NOW() 之类的东西,但为了更好地支持单元测试而将它们全部删除,这有时需要将“现在”设置为特定日期和/或时间。我的查询现在看起来更像'date_from &gt;=' =&gt; FrozenDate::now()-&gt;addDays(10)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多