Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
aiakane16 opened this issue Jun 19, 2018 · 5 comments
Closed

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

aiakane16 opened this issue Jun 19, 2018 · 5 comments
Labels

Comments

@aiakane16
Copy link

aiakane16 commented Jun 19, 2018

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();
@aiakane16 aiakane16 changed the title Can we set the type field to using the base model? Can we set the type of model using the base model? Jun 19, 2018
@jonspalmer
Copy link
Owner

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
Copy link

mazyvan commented Aug 24, 2018

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

@eberkund
Copy link

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

@sarahmarshy
Copy link

@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
Copy link
Owner

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants