How can I make "nullable" one-to-one relationship in the same model, where I don't store alot of null values inside my table? Let me explain the problem:
I have a User model that may be linked with another User model.
Users Table Migration:
$table->uuid('id')->primary();
$table->string('email')->unique();
$table->string('password');
....
I know that I can add a new column to User's table named user_id which references itself, so I can make a one-to-one relationship. But doing this way, will make alot of users with a "null" value within user_id column.
Knowing this, I tried to make a separated table named user_parents in which I store the User's ID and the Related User's ID.
User Parents Table Migration:
$table->uuid('id')->primary();
$table->foreignUuid('user_id')->constrained();
$table->foreingUuid('parent_id')->constrained('users');
...
Then I created a HasOne relationship within User's, and a User/Parent relation within UserParents
User Model:
public function parent(): HasOne
{
return $this->hasOne(UserParent::class);
}
...
UserParent Model:
public function parent(): BelongsTo
{
return $this->belongsTo(UserParent::class, 'parent_id', 'id');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
...
But I to access a User's parent data, I aways have to go thorugh two relations, and this doesn't feel right to me. Is this the intended way, or is there a better way to do it?
Accessing:
echo $user->parent->parent->email;