2014-01-08 2 views
0

모든 CustomerEventCustomerEvent과 관련된 Customer으로 채 웁니다.laravel 객체를 관계로 채우기

개체를 반복하고 $customerevent->customer foreach 개체를 호출하면 해당 이벤트와 관련된 고객을 얻을 수 있지만 모든 단일 이벤트를 반복하지 않고 주 개체의 모든 개체를 채울 수 있습니까?

나는 이런 일을하고 싶지 :

여기
$typeOne = CustomerEvent::typeOne()->get(); 
$customersWithTypeOne = $typeOne->Customers; 

내 코드 :

표 1 : "이벤트"표 1 "CustomerEvent"에 대한

id, customer_id 

모델 :

,338,

표 2 : "고객"표 2 "고객"에 대한

id 

모델 :

<?php class Customer extends BaseModel{ 
    protected $guarded = ['id']; 
} 

EventController :

public function index() 
{ 
    $typeOne = CustomerEvent::typeOne()->get(); 
    $customersWithTypeOne = $typeOne->Customers; 
    dd($customersWithTypeOne); 
} 

답변

1

데이터베이스 스키마에서 고객이 많은 이벤트를 볼 수 있으므로 Customer 모델에서이 관계를 정의하는 것이 좋습니다.

class Customer extends BaseModel{ 
    protected $guarded = ['id']; 

    public function events() 
    { 
     return $this->hasMany('CustomerEvent', 'customer_id'); 
    } 
} 

그런 다음 이벤트와 고객을 조회 할 수 있습니다 :

$customersWithTypeOne = Customer::whereHas('events', function($query){ 
    $query->where('type_id', 1); 
})->get() 
+0

실제로 Laravel 4.0 사용하고 있었다, 그래서 나는이 기능을 얻기 위해 업그레이드했다. 대답 – oBo

+0

$ 고객 = 고객 주셔서 감사합니다 :: whereHas ('이벤트'기능 ($ 쿼리) { \t \t \t $ 질의 -> typeOne(); \t \t}) -> ('이벤트')와 -> 도망(); – oBo

관련 문제