2014-09-03 9 views
0

AB 모델이 묵시적 관계를 사용하여 서로 관련되어 있다고 가정합니다.관련 모델 간의 관계 확인?

A의 인스턴스가 B의 인스턴스와 관련이 있는지 확인하려면 어떻게해야합니까?

예를 들어 A hasMany BA belongsToMany B의 경우 $a$b과 관계가 있는지 확인하고 싶습니다.

내가 관계 객체 인 $a->relatedBs()에 액세스하여이를 확인할 수 있다고 생각하지만 어떻게 알 수 있습니까? laravel의 문서에 나타낸 바와 같이

답변

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 
관련 문제