2016-11-21 1 views
2

나는 많은 관계에 몰두하는 패키지를 많이 만들고 있습니다. 이 관계로 평소처럼 다음과 같이 관계를 정의해야합니다.Laravel 5 동적 모프 방법

public function foos() 
{ 
    return $this->morphToMany('App\Models\Foo', 'barable'); 
} 

분명히 잘 작동하며 여기에는 문제가 없습니다.

정의해야 할 많은 관계가 있지만. 그리고 패키지를 쉽게 구성 할 수 있도록 자동으로 루프를 만들고 싶습니다.

public function __get($name) 
{ 
    if($name == 'foos') { 
     return $this->morphToMany('App\Models\Foo', 'barable'); 
    } 
} 

이 데이터를 검색하는 쿼리를 시작하지 않습니다

나는 다음과 같은 노력했다. 호출되지만 데이터를 반환하지 않습니다.

__call 함수는 나에게도 논리적 인 것처럼 보였지만 Laravel을 깨뜨린 것입니다. 제가 말할 수있는 한 수업에서 부르는 모든 것을 집어냅니다.

다른 대안은 특성을 포함시키고 프로그래머가 게시 가능 파일에서 이러한 관계를 채우는 것입니다.하지만 이는 잘못된 것입니다.

제안 사항?

답변

1

2 단계 답변입니다. 열망하는로드에 대한 수정과 지연로드에 대한 수정이 필요합니다.

eager loader는 model.php에 지정된 __call() 함수를 사용하고 명령문이 실패 할 경우 리디렉션합니다.

public function __call($method, $arguments){ 
    if(in_array($method, ['bars'])) { 
     return $this->morphToMany('App\Bar', 'barable'); 
    } 
    return parent::__call($method, $arguments); 
} 

게으른 로더는 메소드가 존재하는지 여부를 확인합니다. 모델에 추가하고 "OR"문을 추가하면 이러한 작업이 가능해집니다. 원래 함수는 또한 model.php에 있습니다.

public function getRelationValue($key) 
{ 
    // If the key already exists in the relationships array, it just means the 
    // relationship has already been loaded, so we'll just return it out of 
    // here because there is no need to query within the relations twice. 
    if ($this->relationLoaded($key)) { 
     return $this->relations[$key]; 
    } 

    // If the "attribute" exists as a method on the model, we will just assume 
    // it is a relationship and will load and return results from the query 
    // and hydrate the relationship's value on the "relationships" array. 
    if (method_exists($this, $key) || in_array($key, $this->morphs)) { 
     return $this->getRelationshipFromMethod($key); 
    } 
} 
: 추가 : 예상대로

|| in_array($key, $this->morphs) 

함수의 작품을 만들 것 때문에 결과