【问题标题】:Table inheritance in LaravelLaravel 中的表继承
【发布时间】:2016-02-01 10:21:37
【问题描述】:

作为 laravel 的新手,我在正确设置 Laravel 模型时遇到了问题。 在我的 UML 图中,我使用 Generalization 以便我可以从父表中“继承”一些属性:

在我的数据库中,我有以下内容。

实体表

-------------------
| 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 中正确映射我的表格?

【问题讨论】:

    标签: laravel model eloquent uml laravel-5.1


    【解决方案1】:

    这不是继承。它是一个协会。您正在引用 Entity 表中的 ID。

    据我所知,id 用于WorkerRobot,因此您应该使用xor 添加约束。

    【讨论】:

    • 感谢您的宝贵补充。我会相应地纠正我的模型:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2014-09-22
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    相关资源
    最近更新 更多