Reference tables in Laravel 5
I am writing an application that requires 2 tables that are linked to each other using a link table, so there are 3 tables in total.
//-------
Users
//------
id,
name,
email,
password
//----
UserAccountType
//----
id,
name,
description
//---
UserAccountLink
//---
id,
user_id,
type_id,
A user can have multiple account types (Admin, Normal, Developer) ... Also, I have set foreign key constraints.
The only problem is that I don't understand how to link this and I have tried the following:
class User extends Model {
// implementation
public function account_type()
{
$this->hasMany('UserAccountTypeLink', 'id', 'id');
}
}
class UserAccountType extends Model {
// Implementation
}
class UserAccountTypeLink extends Model {
// Implementation
public function user_account()
{
return $this->hasOne('UserAccountType', 'type_id', 'id');
}
}
My expected result is that for example user 1 has an "Admin" and "Developer" account. But at the moment I cannot get the desired result. Any ideas where I'm going wrong?
+3
source to share
1 answer
You don't need a model for the UserAccountTypeLink staging table. Look here for more information on how to create a many-to-many relationship in Speech: http://laravel.com/docs/5.1/eloquent-relationships#many-to-many
+1
source to share