我有一个模型'页的'其拥有一个对许多有关'PageCustomField'(如WordPress的概念定义的字段)。

这个定义领域的模式有两个领域,关键的和价值。什么我想要做的是能够做些什么喜欢下一个的树枝的模板,那里的 page 是的父页模型, custom 是收集定义的领域, email 是的 关键 要查询的定义领域的关系。输出将可以的 value 领域PageCustomField模型。

{{ 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();
    });
}

看过照\数据库\雄辩\模型方法,我看不回调,这将实现这一点,但可以这样做?我可以替代的 firstOrFail() 方法,但宁愿没有。

有帮助吗?

解决方案

我相信你可以用一种 访问 对于这种情况。

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