首页 文章

选择查询中的CakePHP 3格式日期

提问于
浏览
0

我在我的项目中使用CakePHP 3,我想在报告中为 date_joineddate_inactive 字段格式化日期 . 我可以使用带有日期函数的原生选择查询来格式化该字段的日期,但在CakePHP中,我不知道如何在选择查询中集成日期格式 .

$query = $this->CustomersView->find();
                $query->select(['id','contact_person',''date_joined',
                    'date_inactive','comments','status']);
                $query->toArray();

UPDATE

我也试过了CakePHP在线的一个例子resource

$date = $query->func()->date_format([
                   'date_joined' => 'literal',
                    '%m-%d-%y' => 'literal'
                ]);

$query->select(['id','contact_person',''date_joined',
                    'date_inactive','comments','status']);
                $query->toArray();

但它在下面引发了我的错误:

'Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%m-%d-%y)) AS `datejoined`, CustomersView.date_inactive AS `CustomersView__date_' at line 1'

CakePHP生成的SQL查询:

SELECT CustomersView.id AS `CustomersView__id`,
CustomersView.contact_person AS `CustomersView__contact_person`, 
(date_format(date_joined, %m-%d-%y)) AS `datejoined`, 
CustomersView.date_inactive AS `CustomersView__date_inactive`, 
CustomersView.comments AS `CustomersView__comments`, 
CustomersView.status AS `CustomersView__status` 
FROM customers_view CustomersView

任何帮助都非常感谢 . :)

谢谢,

射线

3 回答

  • 1

    如果日期字段在模式中是适当的类型(例如 DATETIME ),那么Cake将返回可以使用普通PHP格式化的DateTime对象 - 您不需要在select中执行此操作 .

    例:

    $query = $this->CustomersView->find();
    $query->select(['id','contact_person','date_joined',
      'date_inactive','comments','status']);
    $array = $query->toArray();
    
    foreach ($array as $row) {
        echo $row["date_joined"]->format("dMY");
    }
    

    例如,假设您的查询只返回一行,此处的 date_joined 字段设置为 2015-12-21 23:55:00 . 上面的代码只会打印出 21Dec2015 .

  • 1

    您可以使用MySQL中的DATE_FORMAT($ field,%d-%m-%Y) .

    Here it is an example:

    $query = $this->CustomersView->find();
                    $query->select(['id','contact_person',''DATE_FORMAT(date_joined, "%d-%m-%Y")',
                        'date_inactive','comments','status']);
    
  • 0

    修复了以下代码的问题:

    $query = $this->CustomersView->find();
    $date = $query->func()->date_format([
                       'date_joined' => 'literal',
                        "'%m-%d-%y'" => 'literal'
                    ]);
    $query->select(['id', 'contact_person', 'date_joined' => $date,
                    'date_inactive', 'comments', 'status']);
    $query->toArray();
    

相关问题