Eloquent - 모델 가져 오기가 완료되면 콜백이 완료됩니다
문제
사용자 정의 필드의 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
. 제휴하지 않습니다 StackOverflow