【问题标题】:How create a query with a join in cakephp如何在 cakephp 中创建一个带有连接的查询
【发布时间】:2025-12-26 16:00:12
【问题描述】:

我需要使用 CakePHP 的 find 方法进行如下查询:

SELECT * FROM fydee.clients_groups join clients on clients_groups.client_id = clients.id where clients.deleted = 0 and group_id = 7;

Client_groups.client_id 字段与clients.id 字段相同,所以这就是加入的内容。我如何在 cakephp 中创建它?

我试过了:

$clients = $this->Groups->find('all', array(
            'joins' => array(
                array(
                    'table' => 'Clients',
                    'alias' => 'ClientsJoin',
                    'type' => 'INNER',
                    'conditions' => array(
                        'ClientsJoin.id = client.id'
                    )
                )
            ),
            'conditions' => array(
                'Group.id' => $_POST['group_id'],
                'Client.deleted' => 0
            )
        ));

【问题讨论】:

    标签: php mysql cakephp join


    【解决方案1】:

    看起来你正在尝试做这样的事情:-

    $this->Group->find('all', [
        'joins' => [
            [
                'table' => 'clients',
                'alias' => 'Client',
                'type' => 'INNER',
                'conditions' => [
                    'Client.id = Group.client_id'
                ]
            ]
        ],
        'conditions' => [
            'Group.id' => $_POST['group_id'],
            'Client.deleted' => 0
        ]
    ]);
    

    当您在joins 中声明alias 时,它就是您要加入的表的别名。因此,遵循 CakePHP 命名约定希望类似于 Client。那么你的加入条件需要是'Client.id = Group.client_id'

    您可能更简单地使用contain(假设您的模型关联设置正确)来获得相同的结果,例如:-

    $this->Group->find('all', [
        'contain' => ['Client'],
        'conditions' => [
            'Group.id' => $_POST['group_id'],
            'Client.deleted' => 0
        ]
    ]);
    

    顺便说一句,你应该在 Cake 中使用 $this->request->data 而不是 $_POST

    【讨论】:

    • 查询发回0条记录。 '查询' => 'SELECT Group.id, Group.name, Group.slidesperad, Group.deleted, Group.@98765430@@.@98765439@.@98765439 。fydee。 @.id = 7 AND Client.deleted = 0 AND Group.deleted = 0', 'params' => array(), 'affected' => (int) 0, 'numRows ' => (int) 0, 'took' => (float) 0
    • 您的问题似乎与您的加入条件有关。你的意思是Client.id = Group.client_id 而不是Client.id = Group.id
    • 我已经修复了查询,连接是问题所在。
    • @RichardHoek 太好了!如果我的回答对您有所帮助,请考虑接受它作为正确答案,以帮助其他与您有类似问题的人。 :-)
    最近更新 更多