2015-11-01 39 views
2

作爲laravel的新手,我在正確設置Laravel模型時遇到了問題。 在我的UML圖,我使用Generalization,這樣我可以「繼承」從父表中的一些屬性: enter image description hereLaravel中的表繼承

在我的數據庫,我有以下。

實體表

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

員表

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

機械錶

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

我的型號分別爲:

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); 
    } 

} 

我的問題是:我做得對嗎,還是有更好的方法在Laravel中正確映射表格?

回答

1

這不是一個繼承。這是一個協會。您正在引用Entity表中的ID。

enter image description here

從我看到的ID被用於任何WorkerRobot所以你應該與xor添加約束。

+0

謝謝你的寶貴補充。我會相應地修正我的模型:) –