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

使用CakePHP模型关联从多个表检索值,cakephp,models,Cakephp,Models,我有一个ProductsController,在其中检索产品数据,还需要检索类别名称。(注意:我的Products表中只有Category_ID),如何使用CakePHP模型关联实现这一点 我看到过一些示例,其中主数据表(在我的示例中是Products表)的ID是关联表中的外键。但是,我的案例略有不同,因为Category_ID(来自次表)是主表(Products表)的一部分 我无法使用CakePHP模型配置检索类别名称。你能帮忙吗 我的ProductsController位于Products表

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

我看到过一些示例,其中主数据表(在我的示例中是Products表)的ID是关联表中的外键。但是,我的案例略有不同,因为Category_ID(来自次表)是主表(Products表)的一部分

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

我的ProductsController位于Products表上,该表具有

ID
Prod_Name
Category_ID
....
我的分类表是

ID
Cat_Name

在我的产品控制器中,我想为正在检索的产品检索Cat_名称。

在产品模型中,使用关联:

var $belongsTo = array(
    'Category' => array(
        'className' => 'Category',
        'foreignKey' => 'category_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);
检索产品数据时,请使用
find
方法:

$this->set('variable', $this->Product->find('all'));
一旦它出现在您的视图中,它就是一个包含所有产品及其类别的数组。 像这样:

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

fzmaster的回答是正确的。当表a中有一个外键对应于表B中的id时,表示模型a“属于”模型B。同时,模型B“有多个”模型a可能存在反向关系

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

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

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

此时,CakePHP的方法将自动检索相关模型,除非您使用
$recursive
或使用行为对其进行限制。

正是我所需要的!