I have simple custom made Entity and Mapper class. Mapper is used to get data from Database, and Entity is a collection object with variables, getter/setter methods and relationships between Entities.
Model\Entity\Category
class Category extends Entity
{
private $id, $name, $link;
// belongs to
private $category;
// has many
private $categories;
// relations - belongs_to, has_many, has_one...
private $belongs_to = array ('category');
private $has_many = array ('categories');
// here goes getters, setters for id, name, category, categories...
}
Model\Mapper\Category
class CategoryMapper extends Mapper
{
public function loadTopNavigation()
{
$categories = array();
$data = $this->db->query('SELECT category.name, category.link, category_master.name AS category_name, category_master.link AS category_link
FROM category
LEFT JOIN category AS category_master
ON category_master.id=category.category_id')
->get();
foreach ($data as $row) {
$categories[] = new Category($row);
}
return $categories;
}
}
Usage
$categoryMapper = new CategoryMapper();
$categories = $categoryMapper->loadTopNavigation();
foreach ($categories as $category) {
echo '<li>' . $category->getName() . ' - ' . $category->getCategory()->getName() . </li>;
}
Obtained array from database:
- name
- link
- category_name
- category_link
Expected array:
- name
- link
- category => array (name, link)
I can get category array if I have 2 queries - first I get category and then second query would be getting master category based on child id and save it to $categories[]['category'];
Is there any suggestions what to do ? I could create method in Mapper class to check all category_ rows and set them in special category = array () or to do that in Entity class... Or is there any other way ?