dpzzkfb1244 2017-07-04 20: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 21: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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?