Assume we have a Person model having a marriedTo relationship to itself. The marriedTo relationship should represent three states:
- Person A is married to Person B.
- Person A is not married.
- It's unknown if Person A is married (and to whom).
What are the possibilities to implement such a relationship in Eloquent (Laravel / Lumen) using a MySQL database. What are the pro and cons of each approach?
What I've thought about so far:
Representing all three stages in just one database field and models property
I could distinguish the three stages in MySQL by having an unsigned integer holding the a) id of married Person B, b) an value which isn't a valid id (e.g. -1) if Person A is not married and c) null if it's unknown.
I could use a similar trick in PHP to reflect the three states in just one variable. In ECMAScript I have the distinction between null and undefined which would reflect my "not married" and "don't know" states quite well. I'm not aware of any similar distinction in PHP. But I could use automatic type conversion. So my models relationship could have the values: a) record of Person B (is married to Person B), b) null (is unknown) and c) false (is not married). But this doesn't look like best practice.
I'm quite sure Eloquent does not support any of these dirty hacks out of the box.
Splitting up the information into two database fields and models properties
What sounds more realistic is to split up the information into two database fields and model properties. So one field and property will hold the reference or being null and the other one will represent if the state is known (true / false). But is there any good strategy to keep that these two fields and properties in sync? So that we can not get into edge cases like there record has a reference but state is unknown / false?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2syGmxE
via IFTTT
Aucun commentaire:
Enregistrer un commentaire