如何使用cakephp中的连接创建查询

时间:2016-03-21 15:24:33

标签: php mysql cakephp join

我需要使用CakePHP查找方法执行以下查询:

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.idfield相同,因此连接的内容是什么。我怎样才能在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
            )
        ));

1 个答案:

答案 0 :(得分:0)

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

$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
    ]
]);

当您在alias中声明joins时,它是您要加入的表的别名。因此,遵循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