如何在cakephp中使用连接创建查询
我需要使用CakePHP find方法执行以下查询:如何在cakephp中使用连接创建查询,php,mysql,cakephp,join,Php,Mysql,Cakephp,Join,我需要使用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.idfield相同,因此这就是连接所在的位置。如何在cakephp中创建它 我试过: $clients = $
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
)
));
看起来您正在尝试这样做:-
$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
]
]);
在联接中声明别名时,它是要联接的表的别名。因此,遵循CakePHP命名约定需要类似于Client
。然后,您的加入条件必须是“Client.id=Group.Client\u id”
您可以更简单地使用包含(假设您的模型关联设置正确)获得相同的结果,如:-
另一方面,你应该在Cake中真正使用$this->request->data
,而不是$\u POST
。查询返回0条记录。”查询“=>”选择组
id
,组
名称
,组
,幻灯片区
,组
删除
,组
修改,组
创建
自fydee
组作为组
内部连接fydee
客户作为客户
开启(客户
id=组
id)其中Group
id
=7和Client
Group
Client.id=Group.Client\u id
而不是Client.id=Group.id
?我已经修复了查询,连接是问题所在。@RichardHoek很棒!如果我的回答帮助了你,请考虑接受它作为正确的答案来帮助别人对你有类似的问题。
$this->Group->find('all', [
'contain' => ['Client'],
'conditions' => [
'Group.id' => $_POST['group_id'],
'Client.deleted' => 0
]
]);