I have these tables:
grades:
id | grade
1 | 1
2 | 2
services:
id | service
1 | service1
2 | service2
comments:
id | comment
1 | comment1
2 | comment2
3 | comment3
comments_services:
id | service_id | grade_id(nullable) | comment_id
1 | 1 | null | 1
2 | 1 | 2 | 2
3 | 2 | 3 | 3
In comments model:
public function services(){
return $this->belongsToMany(Service::class, 'comments_services', 'comment_id', 'service_id', 'id')-
>with('grade');
}
In services model:
public function grade(){
return $this->hasOneThrough(Grade::class, Service::class, 'service_id', 'id', 'id', 'grade_id');
}
The issue is with the grade function it should return the related grade but it returns the first row instead.
This is the query generated:
select `grade_id``, `grade`, `comments_services`.`service_id` as `laravel_through_key` from `grades` inner join `comments_services` on `comments_services`.`grade_id` = `grades`.`id` where `comments_services`.`service_id` in (1, 2, 6, 10)
So if there are multiple comments with service_id in (1,2,6,10) it would return the first one.
I think the solution would be to include the comment_id in the query or condition with comments_services.id.
Also, I tried to split this relation instead of using hasOneThrough:
//comments model
public function services(){
return $this->belongsToMany(Service::class, 'comments_services', 'comment_id', 'service_id', 'id')->with('ser');
}
//services model
public function ser(){
return $this->hasOne(Service::class, 'service_id', 'id')->with('grade')
}
//comments_services model
public function grade(){
return $this->belongsTo(Grade::class, 'grade_id', 'id')
}
This is not working either.
CommentController:
public function edit(Request $request, Comment $comment){
return view('comments.edit', compact('comment'));
}
In the case of hasOneThrough this would be returned for all comments with grades:
"grade" => array:3 [▼
"id" => 1
"grade" => "1"
"laravel_through_key" => 2
]