Home  >  Q&A  >  body text

Model inheritance in Laravel

Suppose I have the following class:

I want Animal as the base class, Dog as a subclass of Animal, and the other two as subclasses of Dog.

What are the best practices in Laravel? Create four models and four separate tables? Or create two tables, one for animals and one for dogs.

Also, if each animal had a "makeSound" function, I could use an interface to implement that and then assume the dog barks, but different dog breeds might have some overrides that make them do something slightly different matter. What I'm confused about is, how do I understand what a Golden Retriever is?

If it were just an animal, I could do this

$animals = Animal::get();

But I'm not sure how to do it:

$daschunds = Daschund::get();

Any suggestions/reading material on this topic would be greatly appreciated. I have some knowledge in object oriented programming but not much in Laravel environment. I read some articles but nothing that covered Laravel specific.

P粉990008428P粉990008428306 days ago326

reply all(1)I'll reply

  • P粉648469285

    P粉6484692852024-01-11 16:26:53

    Since all the models in the plan are animals, you should definitely have an animal table and an animal model.

    Now, if your more specific model behaves differently than a general animal, you can inherit from the model so that their methods handle things correctly. That is, if your differences are only in PHP, then you can have models inherit from each other, referencing the same tables, and your application will judge when and how to operate with different models based on some criteria.

    If your database also has differences, that is, in the case of dogs, you need additional information, then you can build an attribute table for dogs that has a foreign key to the animals table.

    Finally, you can decide to use different tables for each model, in which case it is better to implement an abstract animal class and let the more concrete animal model class extend it in its own way, so that you can Common content is implemented into abstract animal classes.

    As for which of the above methods is better, it depends largely on your specific situation.

    reply
    0
  • Cancelreply