rishal
rishal

Reputation: 3538

Laravel Relationship Between Tables

I have generate the following database table and need to create model form them.

Er Diagram

Creating a model seems to be an easy task, but I am confused how should i define the relationship between two tables. In users table RoleId is foreign key. My question is where and how should I define the relationship (in User model or Role model). Should I use hasOne, hasMany, or belongsTo

Upvotes: 1

Views: 1908

Answers (1)

nesl247
nesl247

Reputation: 106

In your User model

public function roles()
{
    return $this->hasOne('Role', 'id', 'RoleId');
}

In your Role model

public function users()
{
    return $this->belongsTo('User', 'RoleId', 'id);
}

Upvotes: 2

Related Questions