nextras / orm

Orm with clean object design, smart relationship loading and powerful collections.
https://nextras.org/orm
MIT License
310 stars 57 forks source link

How to change entity type in STI? #425

Closed lupo112 closed 4 years ago

lupo112 commented 4 years ago

Hi, im looking for solution, how to change entity type in STI.

I have 2 types: IndividualUser and CompanyUser, both are extending parent class User. These two types are recognited by discriminator property $type - as you described in the docs.

On edit form, i have radio list to select the type (individual or company). However, current user (the user im editing) is already typed as e.g. IndividualUser. When I change the type and fill the fields for company user, i cannot set them to user entity - because it is IndividualUser already.

Do you have any solution to this?

hrach commented 4 years ago

Changing type is not currently possible and I do not plan to support this. You may probably change the type (persist) and refresh to reload entity in correct type.

hrach commented 4 years ago

Oh, refresh probably won't work. 🤔 It will retain the entity, just update its data. Maybe clear, but that's not much suitable... 🤔

lupo112 commented 4 years ago

I was trying that, however, it did not work. Only work-around which work was to define the properties on the parent class as optional. Then I can set them and save the entity. However, I dont think this is a good solution.

I was searching for solutions in other ORMs, but did not find anything usable. (Maybe i use STI in a way it should not be used?)

Only one ORM on ruby was supporting this - using method becomes. So in Nextras ORM it will be something like this: $otherTypeEntity = $entity->becomes(OtherType::class) which will convert the entity to other type. I think this could be a good feature.

hrach commented 4 years ago

Maybe i use STI in a way it should not be used?

... probably. The conversion is quite problematic - we can't assume much about the other entity, so probably all values should be extracted and set (go through setters), validated... not so easy task.

I was thinking that you could do this somehow manually but that would probably require an access to IdentityMap, which is restricted for now.

hrach commented 4 years ago

Closing, current design doesn't allow this and it quite complicated to introduce this (mainly because IdentityMap).