【问题标题】:try to implement the join query in Cakephp尝试在 Cakephp 中实现连接查询
【发布时间】:2013-07-04 13:48:17
【问题描述】:

我正在研究 cakephp 并尝试实现 join 。或者内部连接查询...我现在正在做的是这个

$this->bindModel(array(
    'belongsTo' => array(
        'Contact' => array(
            'className' => 'Contact',
            'foreignKey' => false,
            'conditions' => array(
                'Message.user_id = Contact.user_id',
                'Message.mobileNo = Contact.mobileNo'
            )
        )
    )
), false);

return $message_details = $this->find('all', array(
    'conditions' => array(),
    'fields' => array('DISTINCT mobileNo')
));

此查询正在执行 LEFT JOIN 表.. 我想要的是两个表之间的 joininner join

【问题讨论】:

    标签: sql cakephp mysqli cakephp-2.0 cakephp-2.1


    【解决方案1】:

    您可以在 belongsTo 配置中指定连接类型,如the documentation 中所述。保留默认值,但您可以使用任何有效的连接类型。只需将'type' => 'inner' 添加到配置数组中,您应该会得到如下内容:

    $this->bindModel(array(
        'belongsTo' => array(
            'Contact' => array(
                'className' => 'Contact',
                'foreignKey' => false,
                'conditions' => array(
                    'Message.user_id = Contact.user_id',
                    'Message.mobileNo = Contact.mobileNo'
                ),
                'type' => 'inner' // Simply add this
            )
        )
    ), false);
    

    【讨论】:

      【解决方案2】:

      或者,您可以在不使用 bingModel 的情况下将联接添加到查询中:

      return $message_details = $this->find('all', array(
          'conditions' => array(),
          'fields' => array('DISTINCT mobileNo'),
          'joins'=>array(
              array(
                  'table'=>'contacts,
                  'alias'=>'Contact',
                  'type'=>'INNER',
                  'conditions'=>array(
                      'Message.user_id = Contact.user_id',
                      'Message.mobileNo = Contact.mobileNo'
                  )
              )
          )
      ));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多