如何使用PHP中的Left Joined数据将数据从Mapper保存到Entity

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 ?

I figured it out! Like I said in post above, I created a method inside Mapper class which runs through fetched rows from database and looks if it contains category_ string. If it does, then saves it in in special $category array.

First I wanted to put this method inside Entity class, but what if I switch SQL Mapper to XML or JSON or something like this with different key names, then again I will have problems with saving values properly.

It looks something like this:

foreach ($data as $key => $value) {
    $class = strstr($key, '_', true);
    if (in_array($class, $this->belongs_to)) {
        // adding $key and $value to newly created array $category = array()
    }
}