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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大