Phorce
Phorce

Reputation: 4642

Link Tables in Laravel 5

I am writing an application that requires 2 tables that are linked together 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,

The user is able to have multiple account types (Admin, Normal, Developer)... Also, I have set the foreign keys restraints.

The only problem is that I don't understand how I would link these, 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 output is that, for example, User 1 has the account of an "Admin" and a "Developer" returned. But at the moment, I can't seem to get this desired output. Any ideas to where I am going wrong?

Upvotes: 4

Views: 5780

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

You don't need the model for the intermediate UserAccountTypeLink table. Have a look here to get more info on how to create many-to-many relation in Eloquent: http://laravel.com/docs/5.1/eloquent-relationships#many-to-many

Upvotes: 3

Related Questions