'Laravel - Filter the relation of a relation if it exists
I have an ObjectA. The Object A has a OneToOne relationship with another ObjectB. Object B can have another hasOne relationship to an ObjectC.
| Object A | Object B | Object C |
|---|---|---|
| id (int) | id (int) | id (int) |
| name (string) | meta_data (string) | additinal_meta_data_description (string) |
| object_b_id (int) | is_something (boolean) | |
| is_something (boolean) | object_b_id |
Goal: I would like to filter!
- give me all objects A together with objects B that are A.is_something TRUE.
- At the same time I would like to get the relation to Object C with. If one exists!
Sub-goal: All objects found that have a relationship C should be prioritized and appear at the top of the list. Is this possible at all?
My Query:
$r = ObjectA::where([['is_something', '=', true]]
->whereHas('objectB', function($q) => use($isSomething = true) {
$q->objectC->where('is_something', $isSomething);
});
//----
class ObjectB extends Model
{
use HasFactory;
public function objectC()
{
return $this->hasOne(ObjectC::class);
}
}
Problem I got Exception: Property [objectC] does not exist on the Eloquent builder instance.
Solution 1:[1]
This is the result query if I understood correctly :
$results = ObjectA::where('is_something', true)
->whereHas('objectB', function($subQ) {
$subQ->whereRelation('objectC', 'is_something', true);
})
->get();
reference for the whereRelation : https://laravel.com/docs/9.x/eloquent-relationships#inline-relationship-existence-queries
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 | Marwane Ezzaze |
