Home > Blockchain >  Eloquent Get Collection if it has at least one relation
Eloquent Get Collection if it has at least one relation

Time:03-29

I have a scenario where I have a model A that has 3 relations B, C, and D. I'm trying to get collections in A where it has at least one relation so I don't want {id:1,B:[],C;[],D:[]} But I would accept {id:2,B:[{id:6}],C;[],D:[]} I tried getting them by 3 has but that only gets it if it has all 3. I also tried getting all then checking by if but I want a faster way.

CodePudding user response:

You can use orWhereHas for that

$collectionA = A::where(function($query) {
        $query->whereHas('B')
            ->orWhereHas('C')
            ->orWhereHas('D');
    })
    ->get(); 
  • Related