使用CakePHP模型关联从多个表中检索值

时间:2012-02-20 23:54:55

标签: cakephp models

我有一个ProductsController,我在其中检索Products数据,还需要检索类别名称。 (注意:我的Products表中只包含Category_ID),如何使用CakePHP模型关联来实现?

我见过一些示例,其中主数据表的ID(在我的情况下,Products表)是关联表中的外键。但是,我的情况略有不同,因为Category_ID(来自辅助表)是Main表(Products表)的一部分。

我无法使用CakePHP模型配置检索类别名称。你能帮忙吗?

我的ProductsController在Products表上,有

ID
Prod_Name
Category_ID
....

我的类别表就像

ID
Cat_Name

在我的ProductsController中,我想检索正在检索的产品的Cat_Name。

2 个答案:

答案 0 :(得分:6)

在您的商品模型中,使用关联:

var $belongsTo = array(
    'Category' => array(
        'className' => 'Category',
        'foreignKey' => 'category_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

检索商品数据时,请使用find方法:

$this->set('variable', $this->Product->find('all'));

在View中,它是一个包含所有产品及其类别的数组。 像这样:

<?php
foreach($variable as $itemInTable):
    echo 'Product:' . $itemInTable['Product']['Prod_Name'];
    echo 'Its Category:' . $itemInTable['Category']['Cat_Name'];
endforeach;
?>

答案 1 :(得分:1)

fzmaster的回答是正确的。如果表A中的外键对应于表B中的id,则表示模型A“属于”模型B.同时,模型B“有很多”可能存在反比关系模型为。

在该上下文中,关联非常简单,如果使用Cake naming conventions,则可以使用最少的附加代码关联模型:

class Product extends AppModel{
    var $belongsTo = array( 'Category' );
}

class Category extends AppModel{
    var $hasMany = array( 'Product' );
}

此时,CakePHP的Model::Find()方法将自动检索相关模型,除非您使用$recursive或使用Containable行为限制它。

相关问题