I'm having 3 tables. users, rewards, and gained rewards. I want to get the rewards for each colleague of the user.
I wrote the following api, but it didn't work.
public function getColleaguesGainedRewards(Request $request){
$company_id = $request->company_id;
$colleagues = GainedReward::find(1)->users->where('company_id', $company_id);
$rewards = GainedReward::all();
return response()->json([
"status" => "success",
$colleagues => $rewards,
], 200);
}
And I assigned the following relationship in the gained reward model:
public function users()
{
return $this->hasMany(User::class, 'company_id');
}
public function rewards()
{
return $this->hasMany(Reward::class, 'id');
}
The users table looks as follow:
| id | name | company_id |
|---|---|---|
| 1 | John | 1 |
| 2 | Jack | 1 |
| 3 | Alex | 2 |
The companies table looks as follow:
| id | name |
|---|---|
| 1 | Abc |
| 2 | Def |
The rewards table looks as follow:
| id | name |
|---|---|
| 1 | Day Off |
| 2 | Coffee |
The gained_rewards table looks as follow:
| id | reward_id | user_id |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 2 | 2 |
So I want to get all the rewards for each colleague. For example the result should look as follows:
Get the rewards for each employee at company "Abc":
| John | Jack |
|---|---|
| Day Off | Day Off |
| Coffee |