0

您如何在 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'
));
4

2 回答 2

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'
    )
));
于 2012-12-17T17:45:51.910 回答
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'];
于 2012-12-20T09:48:25.713 回答