donjd86266 2015-09-11 03:44
浏览 38
已采纳

带左连接的cakephp select语句

I have two tables are Servers and ApplicationsGroupsServers, where server_id is foreign key to 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.

$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:

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
  • 写回答

2条回答 默认 最新

  • dsgoj7457 2015-09-11 10:04
    关注

    You should try to create relationships between your models instead of using join queries, but if you really want to use a join query:

    $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',
                )
            )
        )
    ) ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题