2014-09-03 51 views
0

假設AB模型使用雄辯關係相互關聯。檢查相關模型之間的關係?

如何檢查A中的實例是否與B中的實例有關係?

例如在A hasMany BA belongsToMany B的情況下,我想檢查$a是否與$b有關係。

我想我可以通過訪問關係對象$a->relatedBs()來檢查,但我不知道該怎麼做?

回答

1

已經有公關框架正是這個:https://github.com/laravel/framework/pull/4267

$b = B::find($id); 

$as = A::hasIn('relationB', $b)->get(); 

不過泰勒沒有合併,所以你需要whereHas

// to get all As related to B with some value 
$as = A::whereHas('relationB', function ($q) use ($someValue) { 
    $q->where('someColumn', $someValue); 
})->get(); 

// to check if $a is related to $b 
$a->relationB()->where('b_table.id', $b->getKey())->first(); // model if found or null 

// or for other tha m-m relations: 
$a->relationB()->find($b->getKey()); // same as above 

// or something more verbose: 
$a->relationB()->where('b_table.id', $b->getKey())->exists(); // bool