2014-04-06 161 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; 
} 

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

非常感謝酥:)

相關問題