1

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

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

do i need to use both?
No you don't. The only reason you might want to add the users() function to your Role model is so that you can see what users have a specific role.
thanks. One more thing that confuses me is, one user can have only one role but you are using hasMany, is there any explanation for that or is my ER-Diagram wrong?
I corrected my answer. I did write the wrong function in there, should have been hasOne.
@rishal A hasOne in User and belongsTo in Role is a sign of a one-to-one relationship, but your ER diagram seems to indicate a one-to-many relationship (a USER associates to ONE ROLE, a ROLE associates to MANY USER). My guess is that you want to say that a user has one role. To do that, you can simply have a hasOne in User and nothing in Role.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.