Php 检查相关模型之间的关系?
假设Php 检查相关模型之间的关系?,php,laravel,eloquent,relationship,Php,Laravel,Eloquent,Relationship,假设A和B模型使用雄辩的关系相互关联 我应该如何检查来自A的实例是否与来自B的实例有关系 例如,在A有许多B和A属于多个B的情况下,我想检查$A是否与$B有关系 我想我可以通过访问关系对象$a->relatedBs()来检查这一点,但我不知道怎么做?a::has('B')->get() 如laravel文档中所示:该框架中有PR,正是因为此: 但是Taylor没有合并它,所以您需要where has: // to get all As related to B with some value $
A
和B
模型使用雄辩的关系相互关联
我应该如何检查来自A的实例是否与来自B的实例有关系
例如,在A有许多B
和A属于多个B
的情况下,我想检查$A
是否与$B
有关系
我想我可以通过访问关系对象$a->relatedBs()
来检查这一点,但我不知道怎么做?a::has('B')->get()代码>
如laravel文档中所示:该框架中有PR,正是因为此:
但是Taylor没有合并它,所以您需要where has
:
// 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
Tnx,但我不想从与B
实例相关的A
获取实例。请再核对一下这个问题。
// 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