SQL 查询到 CakePHP 翻译

SQL query to CakePHP translation

几天来我一直在努力弄清楚这个(我想很简单)的事情:

我有三个 table 具有这些字段:

  1. 校友:id, nomcognoms
  2. 群组:id
  3. alumnesgrups:id,alumne_id(与 Alumnes.id 相关)和 grup_id(与 Grups.id 相关)。这是一个枢轴table(连接table,关系table...)

我的问题是:

如果我想填充 select 框(在 add.ctp 中,我应该在 AvadiariesController.php 中编码什么) 以及此查询的结果:

SELECT
alumnes.nomcognoms

FROM
alumnes_grups

INNER JOIN grups ON
alumnes_grups.grup_id = grups.id

INNER JOIN alumnes ON
alumnes_grups.alumne_id = alumnes.id

WHERE 
alumnes_grups.grup_id = '16-17 2nB'

ORDER BY
alumnes.nomcognoms

我可以从另一个 table 获得显示字段吗? 我怎样才能看到 'name' 而不是 'id'?

用户 bill 友善地建议我重写(正确?)到:

$alumnesGrups = $this->Avadiaries->AlumnesGrups->Alumnes->find('list',
    ['fields' => ['Alumnes.nomcognoms'], // keep the alias consistent with whatever you define in the join
    'joins' => [['table' => 'alumnes',
                 'alias' => 'Alumnes',
                 'type' => 'INNER',
                 'conditions' => ['Alumnes.id' => 'AlumnesGrups.alumne_id']],
        // mimic the above to join the other table
                ['table' => 'grups',
                 'alias' => 'Grups',
                 'type' => 'INNER',
                 'conditions' => ['AlumnesGrups.grup_id' => '16-17 2nB'],
                 'order' => ['Alumnes.nomcognoms' => 'ASC']]
                ]
               ]
     );

现在 add.ctp 没有报错,但是这个条件没有被应用:

'conditions' => ['AlumnesGrups.grup_id' => '16-17 2nB']

我正好需要这个起点,所以我可以想出一些其他的东西。

试试这样的东西:

$this->AlumnesGrup->find('all',
    array(
        'fields' => array(
            'Alumne.nomcognoms' // keep the alias consistent with whatever you define in the join
        ),
        'joins' => array(
            array(
                'table' => 'alumnes',
                'alias' => 'Alumne',
                'type' => 'INNER',
                'conditions' => array(
                    'Alumne.id = AlumnesGrup.alumne_id
             ),
            // mimic the above to join the other table
        ),
        'conditions' => array(
            'AlumnesGrup.grup_id' => '15-16 2nB'
        ),
        'order' => array(
            'Alumne.nomcognoms ASC'
        )
    )
);

为清楚起见,我将您的查询稍微修改为如下内容:

SELECT
alumnes.nomcognoms

FROM
alumnes_grups

INNER JOIN grups ON
alumnes_grups.grup_id = grups.id

INNER JOIN alumnes ON
alumnes_grups.alumnes_id = alumnes.id

WHERE 
alumnes_grups.grup_id = '15-16 2nB'

ORDER BY
alumnes.nomcognoms

看完这个我终于找到了解决办法document

$alumnesGrups = $this->Avadiaries->AlumnesGrups->find('all', [
'fields' => ['Alumnes.name'], 
'contain' =>['Alumnes', 'Grups'], 
'conditions' => ['Grups.id =' => 1]
]);

我现在的问题是我得到的是 {"Alumnes":{"name":"Angela Smith"}} 而不是普通的 "Angela Smith"。我会继续寻找。