0

我是 cakephp 的新手,我有两个表 tb_product 和 tb_category 我想像下面的 sql 一样选择。我怎么能用 cakephp 做到这一点?

SQL:

SELECT tb_product.id, tb_product.name, tb_category.name 
FROM tb_product 
INNER JOIN tb_category 
WHERE tb_product.cat_id = tb_category.cat_id"

谢谢各位帮手!

tb_product:
----------
id
name
===========

tb_category:
-----------
cat_id
name
==========

先谢谢了!!!

4

1 回答 1

1

您可以在 Cake 模型中为 Product 创建模型关联,以根据 cat_id 外键自动加入到 hasOne 关系中的类别,或者您可以将find()查询作为手动加入来完成:

$results = $this->Product->find('all', array(
    'joins' => array(
        array(
            'table' => 'tb_category',
            'alias' => 'Category',
            'type' => 'INNER',
            'conditions' => 'Category.cat_id = Product.cat_id'
        )
    ),
    'fields' => array(
        'Product.id',
        'Product.name',
        'Category.name'
    )
));

模型关联看起来像这样:

class Product extends AppModel {
    // ...
    public $hasOne = array(
        'Category' => array('foreignKey' => 'cat_id')
    );
}

然后,当您查询您的产品型号时,应该返回匹配的类别:

$results = $this->Product->find('all');
于 2014-09-02T04:26:59.127 回答