Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

  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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading