jonspalmer / single-table-inheritance

A Single Table Inheritance Trait for Eloquent/Laravel
MIT License
249 stars 50 forks source link

Can we set the type of model using the base model? #47

Closed aiakane16 closed 6 years ago

aiakane16 commented 6 years ago

can we set the type of model using the base model. this one is failing to save unless i define a protected static $singleTableType = 'test'; in the base model.

what will this do is it will resolve to that type of model when retreive again. i want to avoid using if else statement to instantiate the child class.

class Base extends Model {

    use SingleTableInheritanceTrait;

    protected static $singleTableTypeField = 'type';

    protected static $singleTableSubclasses = [
        Child::class,
    ];

    protected $fillable = [
        'name',
        'description',
        'type'
    ];
}
....
$base= new Base();
$base->name = 'sample name';
$base->description = 'sample description';
$base->type = 'child'; // this one 
$base->save();
jonspalmer commented 6 years ago

That's not really how you should think about using the type field. You should instantiate the concrete classes you want to create (using a if/else or switch statement) rather than setting the type. There are too many ways the pattern you describe could break. Suppose the Child classes has setters, getters, validation, save hooks etc. None of those are going to get called unless you create a Child class explicitly.

mazyvan commented 6 years ago

@aiakane16 check my posible solution, It might help you #50

eberkund commented 6 years ago

What about for using Laravel implicit binding? https://laravel.com/docs/5.7/routing#implicit-binding

sarahmarshy commented 3 years ago

@jonspalmer, can I ask why this library has a newFromBuilder function if you are supposed to create a new instance of the child class explicitly? I thought your newFromBuilder override was supposed to get around that?

jonspalmer commented 3 years ago

@sarahmarshy newFromBuilder is an internal API used by Eloquent to hydrate model classes before returning the results of a query. It's not intended as a API that any consumer would call directly.