I have three tables like these:
Expense:-
- expense_id
- user_id
User:-
- user_id
- employee_id
Employee:-
- employee_id
- first_name
- last_name
I want to get first_name
and last_name
from the employee table where expense.user_id = user.user_id
, I tried something like bellow, but I did not get the correct data.
Expense model:-
public function users(){
return $this->hasOne(User::class,'user_id','user_id');
}
User model:-
public function employee(){
return $this->hasOne(Employee::class,'employee_id','user_id');
}
And employee model:-
public function users()
{
return $this->belongsTo(User::class,'employee_id');
}
I called to view like this:-
<td>{{$expense->users->employee->first_name ." " . $expense->users->employee->last_name }}</td>
It shows data, but not as expected data.
Where is my mistake and how it should be? please help! thanks!
I believe you're misusing eloquent relationships.
One To One Relationship.
One To Many Relationship
Try this instead.