[英]cakephp select statement with left join
I have two tables are Servers
and ApplicationsGroupsServers
, where server_id
is foreign key to Servers.id
. 我有两个表是Servers
和ApplicationsGroupsServers
,其中server_id
是外键Servers.id
。
I am trying to write a query to select a field called server_name from servers table and left join all data from ApplicationsGroupsServers
table. 我正在尝试编写一个查询,以从服务器表中选择一个名为server_name的字段,并使左连接ApplicationsGroupsServers
表中的所有数据。
$option = array(
'join' => array(
'table' => 'Servers',
'alias' => 's',
'type' => 'left',
'conditions' => array( 's.id = ApplicationsGroupsServers.id' )
)
);
$apps = $this->ApplicationsGroupsServers->find('all', array(
"fields" => array('Servers.server_name'), ($option)
));
$this->set('applications', $apps);
But, when I run a query like shown below. 但是,当我运行如下所示的查询时。 I am able to populate results: 我能够填充结果:
$apps = $this->ApplicationsGroupsServers->find('all', $option);
SQL Query in the back end that runs: 在后端运行的SQL查询:
SELECT ApplicationsGroupsServers.id AS `ApplicationsGroupsServers__id`,
ApplicationsGroupsServers.application_id AS `ApplicationsGroupsServers__application_id`,
ApplicationsGroupsServers.group_id AS `ApplicationsGroupsServers__group_id`,
ApplicationsGroupsServers.server_id AS `ApplicationsGroupsServers__server_id`
FROM applications_groups_servers ApplicationsGroupsServers
left JOIN Servers s ON s.id = ApplicationsGroupsServers.id
However, I am trying to run something like this: 但是,我试图运行这样的事情:
SELECT server_name
FROM applications_groups_servers
LEFT JOIN servers
ON servers.id = applications_groups_servers.server_id
LEFT JOIN groups ON groups.id = applications_groups_servers.group_id
You should try to create relationships between your models instead of using join
queries, but if you really want to use a join
query: 您应该尝试在模型之间创建关系,而不要使用join
查询,但是如果您确实想使用join
查询,请执行以下操作:
$options = array(
'fields' => array(
'Server.name' // Server not Servers
),
'join' => array(
array(
'table' => 'servers',
'alias' => 'Server',
'type' => 'LEFT',
'conditions' => array(
'Server.id = ApplicationsGroupsServers.server_id',
)
),
array(
'table' => 'groups',
'alias' => 'Group',
'type' => 'LEFT',
'conditions' => array(
'Group.id = ApplicationsGroupsServers.group_id',
)
)
)
) ;
Try like this 这样尝试
$this->Server->Behaviors->load('Containable');
$this->Server->bindModel(array('ApplicationsGroups'=>array('classname'=>'ApplicationsGroupsServer','foriegnKey'=>'server_id')));
$app=$this->Server->find(all,array('contain'=>array('ApplicationsGroupsServer.server_name')));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.