【问题标题】:Laravel 5 trouble using Eager LoadingLaravel 5 使用急切加载的麻烦
【发布时间】:2015-12-11 08:32:19
【问题描述】:

所以我有这个问题,通过使用预先加载的人员表获取用户数据。

控制器:

public function staff()
{
    $salon = Salon::find(Session::get('salon'));
    $staff = Staff::where('salon', $salon->id)->with('user')->get();

    return view('dashboard.salon.staff', compact('staff'));
}

查看:

@foreach ($staff as $staff)
    {{ $staff->user->photo }}
@endforeach

型号:

class Staff extends Model {

    protected $table = 'salonStaff';

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

我已尝试使用 dd($staff) 进行故障排除,并且用户关系在控制器中显示为 null,并且在 foreach 中执行 dd($staff->user) 会导致“1”,仅此而已。

【问题讨论】:

  • 外键列是否命名为user?如果是这样,请将其更改为user_id
  • 将其重命名为 user_id 我得到 Column not found: 1054 Unknown column 'user' in 'where clause' (SQL: select count(*) as aggregate from salonStaff where user = 1)

标签: laravel


【解决方案1】:

如果你在用户列中的主键是 = 'user',你应该在用户模型中指定

protected $primaryKey = 'user';

如果不是,当使用关系时,Eloquent 需要一个传统的外键,比如 'user_id' ($tablename_id)

为了确定,尝试在模型关系中指定外键:

return $this->belongsTo('App\User', 'user');

其中第二个参数是表中真正的外键。

也尝试像这样更改您的查询

$staff = Staff::where('salon', $salon->id)->user()->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 2014-08-13
    • 2021-04-23
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    相关资源
    最近更新 更多