1 year ago

What is the best way to implement self reference? Laravel 5.5.4

Posted 1 year ago by cac

I reached a point where I have to implement self reference in an entity of my database. Firstly I tried referencing a parent_id column as a FK but that didn't work quite well when I stored a new record assigning parent_id = id on the database as the new record id doesn't exist before it is saved once.

Then I simply added the column as a nullable integer and then I saved a new record after that I retrieved it and assigned the parent_id to the same value of the id (this is how I am going to identify the root) after which I finally saved it again.

I wonder if this is the best solution in a long run. I am afraid I might not be able to set relationship to automatically retrieve its children or have some sort of difficulties in the future.

Can anyone make me suggestions?

Please sign in or create an account to participate in this conversation.