cakephp-4.x - 从 CakePHP 4 中的数据库表中选择不同的年份
问题描述
我正在尝试使用简单的 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 查询示例来从数据库表中获取唯一年份吗?
解决方案
我认为这可能对你有用:
$years = $this->Events->find() // "all" is the default, no need to specify it
->select(['year' => 'DISTINCT YEAR(Events.date)'])
->order(['year' => 'DESC']);