I have 3 tables as below:
Users Table (has only one phone):
id | Name | phone_id |
---|---|---|
1 | Sam | 1 |
2 | Tom | 2 |
/**
* @return HasOne
*/
public function phone()
{
return $this->hasOne(phones::class);
}
/**
* @return ???
*/
public function key()
{
return ???;
}
Phone Table (has only one key):
id | Name | key_id |
---|---|---|
1 | Nokia | 1 |
2 | Samsung | 2 |
/**
* @return HasOne
*/
public function key()
{
return $this->hasOne(keys::class);
}
Key Table:
id | Name |
---|---|
1 | asd123 |
2 | qwe345 |
/**
* @return belongTo
*/
public function phone()
{
return $this->belongTo(phones::class);
}
I wanted to know how to get the key from the user model:
User::find(1)->key()->Name
2
Answers
you need to work around
hasOneThrough
to get what you need.let’s break it down, based on your schema:
User
belongs to onePhone
phone
belongs toKey
User
belongs toKey
throughPhone
making this clear, we need to declare our
key
relationship inside theUser
model:this will get you directly
key
fromuser
Since a user can have only one phone (as mentioned) and phone has one key you have to use hasOneThrough() relation in model A.
Functions:
Note: For this to work you have to pick top to down approach so make migrations like this User->Phones->Keys.
There is another package that allow belongsToThrough i think its called haven’t used it tho if you want to look into reverse relation lookup (idk why someone need that :))