I've got a little problem here. I have category_id for every product in DB. I also have a category table in DB for categories and their ID. Now i need to put in into view together. I've made add, edit and delete action, also show action, where is category showed with the rest of product description. But now I have a problem with an index action.
In show I did this:
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'
));
}
It's easy, cause during the show action I will get one result from DB, so I know exactly what category_id product has.
But, in index.html I will get all the products from DB and need to iterate them throughout Foreach. That's the place where I need to get a call
$this->getCategoryTable()->getCategory($id);
Since this is a controller method using the sm to use the model method, how should I use this in my index.html view to get the exact category name for every product?
It's massively inefficient to be calling a query to get the category names for each product individually, instead, write a method which will return an array of category names keyed by id in your CategoryTable class
Call the method in your controller action and pass the result to the view ...
In your view, you can loop over your products, and simply access the category name by its
idkey in the$categoriesarrayThe result is just two db calls, instead of one call to get products, and then an additional call to get the category name for each product item individually.