문제

사용자 정의 필드의 WordPress 개념과 같은 일대 다 관계 'PageCustomField'가있는 모델 '페이지'가 있습니다.

이 사용자 정의 필드 모델에는 두 개의 필드, 키 및 값이 있습니다. 내가하고 싶은 것은 나뭇 가지 템플릿에서 다음과 같이 할 수있는 것입니다. 여기서 page는 상위 페이지 모델이며 custom는 사용자 정의 필드 컬렉션이며 email는 쿼리 할 입니다. 필드 관계. 출력은 PageCustomField 모델의 value 필드가 될 것입니다.

{{ page.custom.email }}
.

페이지 모델에 다음을 추가하여이를 수행했습니다.

public $custom = array();

public function extractCustomFields()
{
     foreach ($this->customFields as $customField) {
        $this->custom[$customField->key] = $customField->value;
     }

     return $this;
}
.

는 다음과 같이 호출됩니다.

$page = Page::where('slug', 'home')->firstOrFail()->extractCustomFields();
.

내가 선호하는 것은 정적 부팅 방법과 같이 이것을 자동으로 한 콜백을 갖는 것입니다. 뭔가 ...

public static function boot()
{
    parent::boot();

    // Extract PageCustomField relations into 'custom' array    
    static::fetched(function($model) {
        $model->extractCustomFields();
    });
}
.

vilminite \ database \ eLoquent \ model 메소드를보고,이를 달성 할 콜백을 볼 수 없었지만 수행 할 수 있습니까? firstOrFail() 메서드를 무시할 수는 있지만 오히려하지 않습니다.

도움이 되었습니까?

해결책

"nofollow"> 접근자를 사용할 수 있다고 믿습니다 .

protected $customFields = [
    'email' = 'foo@bar.com'
];

public function getCustomAttribute() {
    return $this->customFields; // array
    //return (object)$this->customFields; // object
}
.

호출 :

$user = MyClass::find(1);

echo $user->custom['email']; // array
//echo $user->custom->email; // object
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top