Laravel 5.4雄辩的关系问题

问题描述:

I need to clear my doubt about Eloquent Relationships. I have 2 models User (which comes with Laravel) and Other is Role which I created. in migration, I added role_id as an additional column as I want every user must have a role now I want to retrieve a user role based on user's id so, I created a public function named roles inside the User Model.

    public function roles(){
        return $this->belongsTo(Role::class);
    }

now when i try to run the query like this.

  App\User::find(1)->roles;

it won't return any result, just empty screen but when I change it to

    public function role(){
        return $this->belongsTo(Role::class);
    }

after that i run code

  App\User::find(1)->role;

now it returns the exact row where the user with id 1 has a proper role. it's confusing why with the roles() function it's not working but with the role() function it's working.

Sorry, If this question is already posted you can redirect me to that question.

Thank You!

You have to specify the foreign key

public function roles()
{
    return $this->belongsTo(Role::class, 'role_id');
}

However, calling it role() is more accurate, since your are assuming that a User can only have one role.