简体   繁体   English

Eloquent 如果至少有一个关系,则获取 Collection

[英]Eloquent Get Collection if it has at least one relation

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.我有一个场景,我有一个 model A,它有 3 个关系 B、C 和 D。我试图在 A 中获得 collections,它至少有一个关系,所以我不想要 {id:1,B: [],C;[],D:[]} 但我会接受 {id:2,B:[{id:6}],C;[],D:[]} 我试着在 3 之前得到它们但是只有当它包含所有 3 个时才会得到它。我也尝试过获取所有然后通过 if 检查,但我想要一种更快的方法。

You can use orWhereHas for that您可以为此使用orWhereHas

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM