2015-01-08 3 views
0

나는 다음과 같은 기관이 있습니다Laravel 열망로드 관계 방법의 결과에 따라 관계

사용자

class User extends Eloquent implements UserInterface, RemindableInterface { 

use UserTrait, RemindableTrait; 

/** 
* The database table used by the model. 
* 
* @var string 
*/ 
protected $table = 'members'; 
protected $primaryKey = 'member_id'; 

public function licences(){ 
    return $this->hasMany('Licence', 'subid', 'member_id'); 
} 

}

라이센스를

class Licence extends \Eloquent { 

protected $table = 'licence'; 
protected $primaryKey = 'id'; 

protected $active = false; 

const DATE_FORMAT = 'Y-m-d'; 

protected $fillable = []; 

public function __construct(){ 
    $this->checkifIsActive(); 
} 

public function owner(){ 
    return $this->belongsTo('User', 'member_id', 'subid'); 
} 

public function checkifIsActive(){ 
    if($this->start_date <= date($this->DATE_FORMAT) && $this->end_date >= date($this->DATE_FORMAT)) $this->active = true; 
} 

}

한 명의 사용자가 여러 개의 라이센스를 가질 수 있으며 사용자의 라이센스는 활성 또는 비활성 일 수 있습니다. 이는 라이센스의 시작 및 종료 날짜에 의해 결정됩니다.

사용자 개체를로드하려고하고 동시에 라이선스를 가져 오려고 시도하지만 활성 상태 인 개체 만 가져옵니다.

라이센스 모델 내에서 개체를 인스턴스화 할 때 '활성'변수를 true로 설정하여 라이센스 상태를 알 수 있습니다.

지금까지 내가 해봤이라는 코드는 다음과 같습니다

return User::findOrFail($id)->with('licence.active')->get(); 

그러나이 꽤 잘하지 않는 경우 - 'licence.active'에서 수행 실제 상태 체크가 없습니다로.

부울 '활성'변수가 '참'으로 설정된 연관된 라이선스와 함께 ID로로드 된 사용자를 어떻게 반환합니까?

답변

0

eager loading 제약 조건을 사용하여 관계를 쿼리 할 수 ​​있습니다.

$user = User::with(array('license' => function($query){ 
    $query->where('start', '<=', Carbon::now()) 
    $query->where('end', '>=', Carbon::now()) 
}))->find($id); 

그러면 활성 상태의 라이센스 만 반환됩니다.

선택적으로 관계 결과를 쿼리 할 수 ​​있습니다.

public function activeLicences(){ 
    return $this->hasMany('Licence', 'subid', 'member_id')->where('start', '<=', Carbon::now())->where('end', '>=', Carbon::now()); 
} 

그런 다음 결과를 얻으려면 다음 작업을 수행해야합니다.

$user = User::with('activeLicenses')->find($id) 

을 참고 :이 테스트되지 않았습니다.

+0

$ id를 매개 변수로 전달하여 ID가 ​​아닌 열 이름을로드해야하는 get 메소드에 전달했습니다. – Amo

+0

@BigPun 업데이트했습니다. find ($ id)를 의미했습니다. –

+0

두 가지 접근법 중 어느 것이 가장 좋을까요? 둘 다 똑같은 결과를 얻었지만 코드 품질면에서 어느 것을 사용하게 될지 알고 있습니다. – Amo