正在检查相关模型之间的关系


Checking for relationships between related models?

假设AB模型使用Eloquent关系相互关联。

我应该如何检查来自A的实例是否与来自B的实例有关系?

例如,在A hasMany BA belongsToMany B的情况下,我想检查$a是否与$b有关系。

我想我可以通过访问关系对象$a->relatedBs()来检查这一点,但我不知道怎么做?

框架正是为此而进行了PR:https://github.com/laravel/framework/pull/4267

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

但是Taylor没有合并它,所以你需要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

A::has('B')->get();

如laravel文档所示:http://laravel.com/docs/eloquent#querying-关系