dqs86517 2017-09-17 03:44
浏览 79
已采纳

Laravel,将一个数据透视表值附加到Auth :: user,有什么缺失/错误?

I'm trying to have Auth::user()->building to return the building ID it is attached to. Right now it's returning Null. What am I doing wrong? Should I explicitly declare something somewhere? Thank you.

My tables :

users (id, name, etc.)

buildings (id, name)

building_user (building_id, user_id) has values ( 7 = building_id, 1 = user_id) with primary key on the two of them combined.


App\User

    ...
    public function building(){
        return $this->belongsTo('App\Building');
    }
    ...

and

App\Building

  ...
  public function users()
  {
    return $this->hasMany('App\User');
  }
  ... 

** EDIT **

I tried doing $building->users on view, and received the error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.building_id' in 'where clause' (SQL: select * from `users` where `users`.`building_id` = 7 and `users`.`building_id` is not null) 

Seems it's trying to not do a relational search. And searching the user table for a building_id column.

  • 写回答

1条回答 默认 最新

  • doucu7525 2017-09-17 04:46
    关注

    First of all you don't need a third table (building_user) unless you have something else in mind.

    You need to make some modifications in your users table.

    • Add a field named building_id for storing the corresponding building_id the user belongs to.
    • Make a relation from building_id to reference id on buildings table.

    Of course remove the third table, you don't need it if you've done the above steps.

    Then Auth::user()->building()->id gives you the building id of the logged in user.

    https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

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

报告相同问题?

悬赏问题

  • ¥15 准备学习小程序搭建,谁能手把手的教我啊?
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)