Home > Blockchain >  Laravel - Filter the relation of a relation if it exists
Laravel - Filter the relation of a relation if it exists

Time:03-24

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!

  1. give me all objects A together with objects B that are A.is_something TRUE.
  2. 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.

CodePudding user response:

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

  • Related