2014-09-03 68 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