Dealing with nested objects (nesting) using an ORM

3

Let's assume that in a system for a bus company I have entities: Line, car and travel. Each has three classes:

The entity itself,

class Linha extends Model
{
   protected $id;
   // outras propriedades.

   public function getId() {
       return $this->id;
   }
   // outros métodos.

Your collection,

class LinhaCollection extends ArrayObject {}

And your mapper.

class LinhaMapper extends Mapper
{
    public function findAll() {
        $sql = "SELECT * FROM 'linhas'";
        return $this->fetchCollection($sql); // Retorna uma coleção de objetos do tipo Linha.
}

So listing all the lines is pretty simple:

$lm = new LinhaMapper;
$linhas = $lm->findAll();

foreach ($linhas as $linha) {
    echo $linha->getNome();
}

/*
 * Linha 123
 * Linha 456
 * Linha 159
 */

I want to list in my View all lines, cars and trips as follows (tree type):

  • Line 123
    • Car 001
      • Travel 1
      • Travel 2
    • Car 002
      • Travel 1
      • Travel 2
  • Line 456 ...

What would be the best way to do this?

Sorry if the explanation was long, I'm a beginner and I do not know if my solution is very obvious. The codes have been simplified to shorten the question

    
asked by anonymous 08.09.2016 / 05:15

1 answer

1

OK you have the three independent entities, isolated from each other. To mount this tree you need one or two entities in your database, suggestions according to my point of view:

1) Relate Lines and Cars. If the same car can be on more than one line it will be an N: N relationship, for example, a Linha_Carro table.

2) In the Travel entity you must have the Car ID, to know which car made each trip , assuming that each trip is only made once, and by a single Car

So far we're just talking about database modeling.

In the OO implementation of the Line class you should create an attribute that will be an array containing Car objects, for example:

class Linha extends Model
{
   protected $id;

   /*
    * @var Carro[] Coleção dos carros vinculados à Linha.
    */
   protected $carros = array();
   // outras propriedades.

   public function getId() {
       return $this->id;
   }
   // outros métodos.

In your Mapper, when you load a Database Line object, after the simple attributes are popular you should populate the $carros attribute of the collection by executing a SELECT in the Carriage table. >     

26.01.2017 / 17:25