Reputation: 4055
Im researching laravel relationships, but i can only see them between 2 tables ... Im wondering if there is such a thing as a one-to-one that works with 3 tables?
For instance, i have the following tables
websites
preferences
websites_preferences
One website has one preferences, but through the websites_preferences table is where the relationship is.
Any help would be great.
Cheers,
Upvotes: 2
Views: 112
Reputation: 101
You don't need websites_preferences table if you only want one-to-one relationship.
But you can do this -> Has Many Through relationship:
class Website extends Model
{
public function preferences()
{
return $this->hasManyThrough('App\Preferences', 'App\Website_preferences');
}
}
Source: https://laravel.com/docs/5.3/eloquent-relationships#has-many-through
Upvotes: 2
Reputation: 697
No need to use the intermediate table for One-to-one relationship.
If you want to use Many-to-many relationship between websites and preferences, You can do like the following.
For this you need the intermediate table 'website_preferences'
class Website extends Model
{
public function preferences()
{
return $this->belongsToMany('App\Preference', 'website_preferences', 'website_id', 'preference_id');
}
}
class Preference extends Model
{
public function websites()
{
return $this->belongsToMany('App\Website', 'website_preferences', 'preference_id', 'website_id');
}
}
Refer this link, it might be helpful https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
Upvotes: 1
Reputation: 3157
Actually you don't need a third table for one-to-one relationship. Third table is for many-to-many. You can use primary key
of preferences
table as foreign key of websites
table.
Upvotes: 0