我有一个ProductsController,我在其中检索Products数据,还需要检索类别名称.(注意:我的Products表中只包含Category_ID),如何使用CakePHP模型关联来实现?
我见过一些示例,其中主数据表的ID(在我的情况下,Products表)是关联表中的外键.但是,我的情况略有不同,因为Category_ID(来自辅助表)是Main表(Products表)的一部分.
我无法使用CakePHP模型配置检索类别名称.你能帮我吗?
我的ProductsController在Products表上有
ID
Prod_Name
Category_ID
....
Run Code Online (Sandbox Code Playgroud)
我的类别表就像
ID
Cat_Name
Run Code Online (Sandbox Code Playgroud)
在我的ProductsController中,我想检索正在检索的产品的Cat_Name.
小智 6
在您的产品型号中,使用关联:
var $belongsTo = array(
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Run Code Online (Sandbox Code Playgroud)
检索产品数据时使用find
方法:
$this->set('variable', $this->Product->find('all'));
Run Code Online (Sandbox Code Playgroud)
一旦进入View,它就是一个包含所有产品及其类别的数组.像这样:
<?php
foreach($variable as $itemInTable):
echo 'Product:' . $itemInTable['Product']['Prod_Name'];
echo 'Its Category:' . $itemInTable['Category']['Cat_Name'];
endforeach;
?>
Run Code Online (Sandbox Code Playgroud)