Cakephp 3:如何在 queryBuilder 中为关联数据添加顺序?

Cakephp 3 : How to add order in queryBuilder for associative data?

这里我有一个事件字段,它与 passwords.I 相关,需要按 download_count DESC 对所有密码进行排序。所以我尝试了下面的代码。它没有给我任何错误,但 desc 不工作。

 $event = $this->Events->get($id, [
                  'contain' => [
                      'EventPasswordAll.Passwords' => [
                          'queryBuilder' => function (Query $q) {
                              return $q->order(['download_count' => 'DESC']);
                          }
                      ]
                  ]
             ]);

我也试过了

 return $q->order(['Passwords.download_count' => 'DESC']);

我收到查询

SELECT EventPasswordAll.id AS `EventPasswordAll__id`, EventPasswordAll.event_id AS `EventPasswordAll__event_id`, EventPasswordAll.password_id AS `EventPasswordAll__password_id`, Passwords.id AS `Passwords__id`, Passwords.name AS `Passwords__name`, Passwords.collection_id AS `Passwords__collection_id`, Passwords.photo_count AS `Passwords__photo_count`, Passwords.download_count AS `Passwords__download_count`, Passwords.created AS `Passwords__created`, Passwords.expires_at AS `Passwords__expires_at`, Passwords.recommended AS `Passwords__recommended`, Passwords.accepted AS `Passwords__accepted`, Passwords.user_id AS `Passwords__user_id` FROM event_password_all EventPasswordAll INNER JOIN passwords Passwords ON Passwords.id = (EventPasswordAll.password_id) WHERE EventPasswordAll.event_id in (14)

如何在 queryBuilder 中为关联数据添加顺序?

EventPasswordAll belongsTo Passwords 的关联,passwords table 记录将通过连接检索,如查询中所示。在这种情况下,没有 Passwords 的查询,因此不会调用查询生成器。

您必须为 EventPasswordAll 查询构建器设置顺序,例如

$event = $this->Events->get($id, [
    'contain' => [
        'EventPasswordAll' => [
            'queryBuilder' => function (Query $q) {
                return $q->order(['Passwords.download_count' => 'DESC']);
            },
            'Passwords'
        ]
    ]
]);