2017-11-13 3 views
0

두 모델이 서로 연결되어 있습니다.JOIN 테이블의 Eloquent where 절 - Laravel 5.5

class Company extends Model { 
    public function addresses() { 
     return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address'); 
    } 
} 

class Address extends Model { 
} 

내 JOIN 테이블에 활성이라는 열이 있습니다. 회사에서 모든 활성 주소를 가져올 수 있습니까? 아니면 JOIN 테이블에 where 절을 구현할 수 있습니까?

감사합니다.

+0

다음 질문에 대한 답변을 알려주십시오. https://laravel.com/docs/5.5/eloquent-relationships –

+0

예, 맞습니다. 나는 피벗 테이블이라는 용어를 몰랐다. :-) – sam918

답변

1

일반적으로 피벗 테이블이라고하는 "JOIN 테이블"이라고하는 테이블입니다. 당신은 wherePivot 방법을 사용하여 모든 활성 기록을 가져올 수 :

$company = Company::first(); 
$activeAdresses = $company->addresses()->wherePivot('active', 1); 

또는 직접 모델의 관계를 정의 할 수 있습니다 :

class Company extends Model { 
    public function activeAddresses() { 
     return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address') 
        ->wherePivot('active', 1); 
    } 
} 

항을 참조 필터링 관계를 통해 중간 테이블 열Eloquent documentation

을의를
+1

또는 [중간 테이블 열을 통한 관계 필터링] (https://laravel.com/docs/5.5/eloquent-relationships#many-to-many)과 같은 모델에서 직접 정의하십시오. –