The error message suggests that the column 'currentAssignment.rank' is not found in the field list. This error occurs because the 'currentAssignment' relationship is not being loaded correctly in the query.
To fix this issue, you need to make sure that the 'currentAssignment' relationship is properly defined and loaded in the query. Here's the solution:
- Make sure that the 'Assignment' model is imported at the top of the User model by adding the following line:
use App\Models\Assignment;
- In the User model, update the 'currentAssignment' relationship method to include the 'Assignment' model:
public function currentAssignment()
{
return $this->hasOne(Assignment::class)
->where('effectivedt', '<=', now())
->orderBy('effectivedt', 'desc')
->orderBy('id', 'desc');
}
- In the Training controller, make sure that the 'User' model is imported at the top of the file:
use App\Models\User;
- Finally, update the query to load the 'currentAssignment' relationship correctly:
$roster = User::with('currentAssignment')
->select(
'users.id',
'users.prefix',
'users.firstname',
'users.middlename',
'users.lastname',
'users.suffix',
'users.status',
'users.empnumber',
'assignments.rank',
'assignments.shift',
'assignments.station'
)
->join('assignments', 'users.id', '=', 'assignments.user_id')
->where('users.status', 1)
->orderBy('users.lastname', 'asc')
->orderBy('users.firstname', 'asc')
->orderBy('assignments.division', 'asc')
->orderBy('assignments.shift', 'asc')
->orderBy('assignments.station', 'asc')
->get();
Note that I've changed 'currentAssignment.rank' to 'assignments.rank' in the select statement, as the 'currentAssignment' relationship is loaded as 'assignments' due to the join.
This should resolve the issue and load the 'currentAssignment' relationship correctly in the query.