我有4个表(ApplicationsGroupsServersTable,ApplicationsTable,ServersTable,GroupsTable)。我试图在下面的代码中使用CakePHP中的左连接,但我得到了SQL异常:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Group ON Group.id = ApplicationsGroupsServers.group_id' at line 1
以下是我在ApplicationsGroupsServersController中的代码:
$option =array(
'fields' => array(
'Server.server_name',
'Group.group_name'
),
'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' )
)
)
);
$apps = $this->ApplicationsGroupsServers->find('all', $option);
$this->set('applications', $apps);
以下是我的关联:
ApplicationsGroupsServersTable:
$this->belongsTo('Applications', [
'foreignKey' => 'application_id'
]);
$this->belongsTo('Groups', [
'foreignKey' => 'group_id'
]);
$this->belongsTo('Servers', [
'foreignKey' => 'server_id'
]);
ApplicationsTable:
$this->hasMany('ApplicationsGroupsServers', [
'foreignKey' => 'application_id'
]);
GroupsTable:
$this->hasMany('ApplicationsGroupsServers', [
'foreignKey' => 'group_id'
]);
我认为我的同事没有正确设置,但是当我用一张桌子运行左连接时,我就是获取数据的表格。以下是适用的代码:
$option =array(
'fields' => array(
'Server.server_name',
// 'Group.group_name'
),
'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' )
// )
)
);
$apps = $this->ApplicationsGroupsServers->find('all', $option);
$this->set('applications', $apps);