dpzzkfb1244 2017-07-04 12:55
浏览 25
已采纳

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!

  • 写回答

1条回答 默认 最新

  • dsqpx86002 2017-07-04 13:22
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部