2014-04-06 93 views
0

我在这里遇到了一些问题。我对DB中的每个产品都有category_id。我也有类别和他们的ID在DB中的类别表。现在我需要一起放入视野。我做了添加,编辑和删除操作,还显示了操作,其中的类别显示在产品描述的其余部分。但是现在我遇到了索引操作的问题。Zend Framework:使用控制器方法调用模型方法

在节目我这样做:

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中,我将从数据库获取所有产品,并需要通过foreach来迭代它们。这就是我需要得到调用

$this->getCategoryTable()->getCategory($id); 

由于地方,这是用SM使用模型方法控制方法,我应该如何使用这在我index.phtml视图为每一个产品得到确切的类别名称?

回答

1

这是大量低效是调用查询单独获得每个产品类别名称,而是写这将返回ID在你CategoryTable类

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关键在访问类别名称0阵列

// index.phtml 
<ul> 
<?php foreach ($products as $product) : ?> 
    <li>Product category name is : <?= $categories[$product->category_id]; ?></li> 
<?php endforeach; ?> 
</ul> 

结果是只有两个调用数据库,而不是一个调用来获取产品,然后,再调用单独获得每个产品的类别名称。因为我用

cant use object type as array

这事,因为我查询没有返回我$result['id']$result['name']

+0

非常感谢酥:)我考虑做这种方式,但不知何故,我卡住了,你真的帮助我。 :) –

0

一切工作,但我想补充别人,当我用你的榜样,它扔错误TableGateway并没有返回$result->id$result->name所以最终的功能如下:

public function getCategoryNames() 
{ 
    $results = $this->fetchAll(); 
    $categories = array(); 

    foreach ($results as $result) { 
     $categories[$result->id] = $result->name; 
    } 

    return $categories; 
} 

其他一切工作以及酥说:)

非常感谢酥:)

相关问题