那么我该如何解决这个问题呢?它给了我:
注意(8):未定义的变量:产品 [APP / View / Categories / category_filter.ctp,第10行]警告(2): 为foreach()提供的参数无效 [APP / View / Categories / category_filter.ctp,第10行]
<? if (!empty($categories)) { ?>
<? foreach($categories as $row): ?>
<h1>Category: <?= $row['Category']['category'] ?></h1>
<table>
<tr>
<th>Name</th><th>Description</th><th>Price</th><th>Category</th>
<th>Thumbnails</th>
</tr>
<? foreach($products as $row): ?>
<tr><<td>
<?=$row['Product']['name']?>
</td><td>
<?=$row['Product']['description']?>
</td><td>
<?=$row['Product']['price']?>
</td><td>
<?=$row['Product']['category_id']?>
</td><td>
<?
if(!empty($row['Picture'])){
?>
<?= $this->Html->image('/img/'. $row['Picture'][0]['filename'], array('width'=>'50', 'alt'=>$row['Picture'][0]['title'])); ?>
<p><?= $row['Picture'][0]['description']; ?></p>
<? } ?>
</td><tr>
<? endforeach; ?>
<? endforeach; ?>
</table>
<? } ?>
在控制器中
function category_filter($category_id) {
$this->set('categories',$this->Category->findAllById($category_id));
}
答案 0 :(得分:1)
您可以通过制作Category Model class
来完成此操作。
//app/Model/Category.php
class Category extends AppModel
{
public $name = 'Category';
public $useTable = 'categories';
public $primaryKey = 'id';
public $hasMany = array('Products' => array('className' => 'Product',
'foreignKey' => 'category_id'
));
}
//app/Model/Product.php
class Product extends AppModel
{
public $name = 'Product';
public $useTable = 'products';
public $primaryKey = 'id';
}
在您的控制器中:
function category_filter($category_id) {
$this->set('category_details',$this->Category->findById($category_id));
}
在您看来:
<h1>Category: <?php echo $category_details['Category']['category'] ?></h1>
<table>
<tr>
<th>Name</th><th>Description</th><th>Price</th><th>Category</th>
<th>Thumbnails</th>
</tr>
<?php if(!empty($category_details['Products'])): foreach($category_details['Products'] as $row): ?>
<tr><td>
<?php echo $row['Product']['name']?>
<?php echo $this->Html->image('/img/'. $row['Picture'][0]['filename'], array('width'=>'50', 'alt'=>$row['Picture'][0]['title'])); ?>
<p><?php echo $row['Picture'][0]['description']; ?></p>
<?php } ?>
</td><tr>
<?php endforeach;endif; ?>
因为我对你的Picture Model
并不太了解。请在您的产品型号中为该型号进行关联。
答案 1 :(得分:0)
<?php
function category_filter($category_id) {
$this->set('categories',$this->Category->findAllById($category_id));
$products=$this->Product->find('all');
$this->set(compact('products'));
}
?>
设置您的产品变量