Laravel 7: 使用自定义外键调用数据显示错误

Laravel 7: Calling data with a custom foreign key shows error

我有一个部门table。这是一个列名 created_by。它存储来自用户 table 的 ID。我想从 created_by 列的 ID 中调用用户名。但它显示错误 Column not found: 1054 Unknown column 'users.department_id' in 'where clause'

部门模型:

 public function user(){
    return $this->hasMany(User::class);
}

用户模型:

 public function department(){
    return $this->belongsTo(Department::class, 'created_by');
}

控制器:

 public function index(){
    $departments = Department::where('deletion_status', 0)->orderBy('department', 'asc')->get();
    return view('admin.department_manage', compact('departments'));
}

Blade 文件:

   @foreach($departments as $row)
       <tr>
          <td>{{ $loop->iteration }}</td>
          <td>{{ $row->user->name }}</td>
       </tr>
   @endforeach

谁能帮我找出解决办法?

您指定了 laravel 错误的关系。这样做:对于用户模型 departments() { return $this-> hasMany(Department::class, 'created_by')} 然后对于部门模型:user(){return $this->belongsTo(User::class, ' created_by', 'id')}. 调用将是:departments= Department::where('deletion_status', 0)->with('user')->get() 部门集合中的每个元素都将包含有关用户的信息。 ,例如可以这样获得 department -> user->name