'Laravel 7: Calling data with a custom foreign key shows error
I have a department table. Here is a column name created_by. It stores the id from users table. I want to call the users name from created_by column's id. But it shows error Column not found: 1054 Unknown column 'users.department_id' in 'where clause'
Department Model:
public function user(){
return $this->hasMany(User::class);
}
User Model:
public function department(){
return $this->belongsTo(Department::class, 'created_by');
}
Controller:
public function index(){
$departments = Department::where('deletion_status', 0)->orderBy('department', 'asc')->get();
return view('admin.department_manage', compact('departments'));
}
Blade file:
@foreach($departments as $row)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $row->user->name }}</td>
</tr>
@endforeach
Can anyone please help me to find out the solutions?
Solution 1:[1]
you specified laravel wrong relationships. do this: for the user model departments() { return $this-> hasMany(Department::class, 'created_by')} Then for the department model: user(){return $this->belongsTo(User::class, ' created_by', 'id')}. The call would be: departments= Department::where('deletion_status', 0)->with('user')->get() Each element in the departments collection will have information about a user. , which can be obtained for example like this department -> user->name
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
