如何在CakePHP中执行连接?

时间:2012-12-17 17:20:53

标签: php cakephp join

如何在CakePHP中执行连接,例如下面的MySQL连接?

SELECT *
FROM yarns y
JOIN yarn_brands yb
JOIN contents ct
WHERE y.id = ct.yarn_id
AND yb.id = y.yarn_brand_id
AND ct.material_id = 2

我试图寻找答案,但我找不到有用的东西。 我发现了一些关于“包含”的内容,我尝试了这个但是我得到的结果是它生成的查询包括请求加入的表的连接。

$this->Message->find('all', array(
    'contain' => array('User')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

2 个答案:

答案 0 :(得分:1)

CakePHP使这一切变得非常简单,只要您已阅读有关模型关系的书籍并相应地设置了模型和数据库表。这是CakePHP的一个非常重要的部分,它将构成你的很多应用程序。如果您了解如何以“蛋糕”的方式做到这一点,它将使您的生活更轻松。

http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

对于您的MySQL示例,请尝试此代码。显然我不确切知道你的模型关系是什么,但这是基于MySQL的猜测。

// app/Model/Yarn.php
class Yarn extends AppModel {

    public $belongsTo = array('YarnBrand');

    // You might need this as $hasOne instead, I can't tell from the MySQL alone.
    public $hasMany = array('Content');

}

// app/Model/YarnBrand.php
class YarnBrand extends AppModel {

    public $hasMany = array('Yarn');

}

// app/Model/Content.php
class Content extends AppModel {

    public $belongsTo = array('Yarn');

}

查找所有纱线的代码,以及它们的纱线和内容

$this->Yarns->find('all', array(
    'conditions' => array(
        Content.material_id' => 2
    ),
    'contain' => array(
        'YarnBrand',
        'Content'
    )
));

答案 1 :(得分:0)

这是我最终的加入:

            $options['contain'] = '';
            $options['joins'][0]['table'] = 'contents';
            $options['joins'][0]['alias'] = 'cont';
            $options['joins'][0]['conditions'] = 'Yarn.id = cont.yarn_id';
            $options['joins'][1]['table'] = 'yarn_brands';
            $options['joins'][1]['alias'] = 'yb';
            $options['joins'][1]['conditions'] = 'yb.id = Yarn.yarn_brand_id';
            $options['fields'] = array('Yarn.name');
            $options['conditions']['cont.material_id'] = $this->request->data['Yarn']['material_id'];
            $options['conditions']['Yarn.yarn_brand_id'] = $this->request->data['Yarn']['yarn_brand_id'];