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.

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