我在这里有一个小问题。我对数据库中的每个产品都有category_id。我在DB中也有类别表,以获取类别及其ID。现在,我需要一起考虑。我进行了添加,编辑和删除操作,还进行了显示操作,其中类别与其他产品说明一起显示。但是现在我索引操作有问题。
在表演中我这样做:
public function getProductTable()
{
if (!$this->productTable) {
$sm = $this->getServiceLocator();
$this->productTable = $sm->get('Product\Model\ProductTable');
}
return $this->productTable;
}
public function getCategoryTable() {
if(!$this->categoryTable){
$this->categoryTable = $this->getServiceLocator()
->get('Product\Model\CategoryTable');
}
return $this->categoryTable;
}
public function showAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('product', array(
'action' => 'add'
));
}
try {
$product = $this->getProductTable()->getProduct($id);
$category = $this->getCategoryTable()->getCategory($product->category_id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('product', array(
'action' => 'index'
));
}
这很容易,因为在showAction期间,我将从DB获得一个结果,所以我确切地知道category_id产品具有什么。
但是,在index.phtml中,我将从DB获得所有产品,并且需要遍历foreach对其进行迭代。那是我需要打电话的地方
$this->getCategoryTable()->getCategory($id);
因为这是使用sm来使用模型方法的控制器方法,我应该如何在index.phtml视图中使用它来获取每个产品的确切类别名称?
调用一个查询以分别获取每个产品的类别名称的效率非常低,相反,编写一个方法将返回一个类别名称数组,该类别名称数组由您的CategoryTable类中的ID组成]
public function getCategoryNames() { // query to get list of names and ids // return array of category names, keyed by id $categories = array(); foreach ($results as $result) { $categories[$result['id']] = $result['name']; } return $categories; }
在控制器操作中调用该方法并将结果传递给视图...
public function indexAction() { $categories = $this->getCategoryTable()->getCategoryNames(); $products = $this->getProductTable()->getProducts(); return new ViewModel(array( 'categories' => $categories, 'products' => $products, )); }
在您看来,您可以循环浏览产品,只需通过
id
数组中的$categories
键即可访问类别名称
// index.phtml <ul> <?php foreach ($products as $product) : ?> <li>Product category name is : <?= $categories[$product->category_id]; ?></li> <?php endforeach; ?> </ul>
结果是只有两个数据库调用,而不是一个获取产品的调用,然后是一个额外的调用,分别获取每个产品项的类别名称。
一切正常,但是我会为其他人补充,当我使用您的示例时,它抛出了错误:
好吧,我认为您可以直接将结果呈现给视图,因为我们都在与MVC一起工作,因为所有逻辑都在控制器上使用,有时您需要在独立组件上很好地分工,所以这样做有点不干净为此,您创建了一个函数,就像我的朋友一样,在我之前,他们为您提供了语法,因此您将编写类似于
public function name of your function()
{
//fetching the result of your model query them all or one
return your result
}