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 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题