按 belongsToMany 关联中的字段排序

Order by a field in belongsToMany association

我有很深的关联,我想知道是否可以通过 BTM 关联中包含的字段对结果进行排序:

$modeles = $this->Caracteristiques
        ->find()
        ->contain(['ModeleElements.ModeleOuvrages' => function ($q) {
            return $q
                ->where([
                    'ModeleOuvrages.couche_id' => 2,
                    'ModeleOuvrages.compte_client_id' => $this->Auth->user('compte_client_id')
                ]);
        }]);

这是我的查询,我想要按 "ModeleOuvrages" 关联中的字段 "nom" 排序的结果集。

是否可以通过 "ModeleOuvrages.nom" 获取所有 "caracteristiques" 订单?

编辑:我这样做了:

$modeleOuvrages = $this->ModeleOuvrages
        ->find()
        ->where([
            'couche_id' => 2,
            'compte_client_id' => $this->Auth->user('compte_client_id')
        ])
        ->select([
            'ModeleOuvrages.nom',
            'ModeleElements.nom',
            'Caracteristiques.nom',
            'Caracteristiques.type'
        ])
        ->matching('ModeleElements.Caracteristiques')
        ->order(['ModeleOuvrages.nom', 'ModeleElements.nom', 'Caracteristiques.nom']);

而且效果很好。我们也可以使用更详细的包含来做到这一点。

是的,当使用 matching('Deep.Nested.Table') 时,您将能够对 Table 的任何列进行排序。

请记住,匹配将创建 INNER JOINs,并且它可能会在结果中重复行。您可以使用 $query->distinct(['MainTable.id']) 删除重复项。