Model Inheritance in Laravel

前端 未结 4 737
别那么骄傲
别那么骄傲 2020-12-23 21:51

i\'m currently working with Laravel and I\'m struggling with the fact that every model needs to extend from Eloquent and I\'m not sure how to implement a model Hierarchy

4条回答
  •  时光说笑
    2020-12-23 22:30

    Even though I like the Polymorphic Relations (PR) approach slightly better than the Single Table Inheritance (STI), it still does not feel anything like a true inheritance approach. From the domain (e.g. a UML Class Diagram) point of view, it is like trying to use a composition relationship instead of inheritance.

    From a database consistency point of view the polymorphic relation by itself is already a very weird solution in Laravel (IMHO). As there can be no single field that is a foreign key to multiple tables, this can lead to joining ID's that should not be joined. And inverse relationships that are not obeyed.

    Although I'm not actually describing a solution to the problem, I'd propose a different approach than PR and STI. This solution would be similar to Hibernate's table-per-subclass approach. I think that Dauce's extension to Eloquent is going in the same direction, except there seem to be a few implementation issues still.

    From a database point of view, a table per subclass would also mean that the super-class contains one column per direct subclass. Then you can put foreign key constraints on the (non-null) id's and properly use the relationships. However, there should still be some extra logic in Laravel's magic Eloquent class that turns the requested object into the right type.

    So for me, functionally, the Eloquent models should properly inherit on the PHP side, while the database can still use the foreign key constraints.

提交回复
热议问题