dimanche 1 novembre 2015

Table inheritance in Laravel

As a newbie to laravel, I have a problem with setting up my Laravel models correctly. In my UML Diagram, I'm using Generalization so that I can "inherit" some attributes from the parent table: enter image description here

In my database, I have the following.

Entity table

-------------------
| id | identifier |
-------------------
| 1  |  AZX-C56   |
-------------------
| 2  |  AZX-C06   |
-------------------
| 3  |  MZX-9F1   |
-------------------
| 4  |  MZX-X09   |
-------------------

Worker table

---------------------------------------------
| id  | entity_id | firstname | lastname |..|
---------------------------------------------
|  1  |     1     |   Jean    |  Michel  |..|
---------------------------------------------
|  2  |     2     |   Jane    |    Doe   |..|
---------------------------------------------

Machine table

----------------------------------------------
| id  | entity_id |    Type   | Description  |
----------------------------------------------
|  1  |     3     |  XU-09-A  |  lorem ipsum |
----------------------------------------------
|  2  |     4     |  XZ-24-U  |  lorem ipsum |
----------------------------------------------

My models respectively:

class Entity extends Model {
     protected $fillable = ['identifier'];

     public function worker(){
         return $this->hasOne(Worker::class);
     }
     public function machine(){
         return $this->hasOne(Machine::class);
     }
}
class Worker extends Model {
     protected $fillable = ['entity_id','firstname','lastname'];

     public function entity(){
         return $this->belongsTo(Entity::class);
     }

}
class Machine extends Model {
     protected $fillable = ['entity_id','type','description'];

     public function entity(){
         return $this->belongsTo(Entity::class);
     }

}

My question is: Am I doing it right, or is there a better way to map my tables correctly in Laravel ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire