【问题标题】:Select distinct years from a database table in CakePHP 4从 CakePHP 4 中的数据库表中选择不同的年份
【发布时间】:2021-12-09 21:05:38
【问题描述】:

我正在尝试使用简单的 SQL DISTINCT 查询从 CakePHP 4 中的数据库表中检索不同年份的列表。

在 CakePHP 2 中,这非常简单。我在控制器函数中使用了以下行:

$this->set('years', $this->Event->findAll(null, array('DISTINCT YEAR(Event.date) as year'), 'date DESC'));

在 CakePHP 4 中,查询构建器是不同的,我一直在努力想出类似的东西。我觉得最接近的可比性是:

$years = $this->Events->find('all', array('fields' => array('DISTINCT YEAR(date) as year'), 'order' => array('year DESC')));
$this->set(compact('years'));

但是,这会产生一个完全不正确的 SQL 查询,它远非有效。我已经尝试按照他们的指示进行操作,但我想出的一切都失败了。

有人有一个简单的 CakePHP 4 查询示例来从数据库表中获取唯一年份吗?

【问题讨论】:

    标签: cakephp-4.x


    【解决方案1】:

    我认为这可能对你有用:

    $years = $this->Events->find() // "all" is the default, no need to specify it
        ->select(['year' => 'DISTINCT YEAR(Events.date)'])
        ->order(['year' => 'DESC']);
    

    【讨论】:

    • 非常感谢!我有一些接近于此的东西,但语法不太正确。非常感谢。
    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2022-01-16
    • 2015-12-26
    • 2012-09-24
    • 1970-01-01
    • 2020-08-07
    相关资源
    最近更新 更多