0

ここで少し問題があります。DB 内のすべての製品に 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'
         ));
     }

簡単です。show アクション中に DB から 1 つの結果を取得するため、category_id 製品の正確な内容がわかります。

しかし、index.html では、DB からすべての製品を取得し、Foreach 全体で反復する必要があります。それは私が電話を受ける必要がある場所です

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

これはモデル メソッドを使用するために sm を使用するコントローラー メソッドであるため、すべての製品の正確なカテゴリ名を取得するには、index.html ビューでこれをどのように使用すればよいですか?

4

3 に答える 3

0

すべてが機能していますが、他の人のために追加します。あなたの例を使用すると、エラーがスローされました:

オブジェクト型を配列として使用できません

これが発生したのは、クエリが返されなかったため、 TableGateway を使用していたため$result['id']返されたため、最終的な関数は次のようになります。$result['name']$result->id$result->name

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

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

    return $categories;
}

クリスプが述べたように、他のすべてはうまく機能しています:)

どうもありがとうクリスプ:)

于 2014-04-08T09:43:40.743 に答える