【问题标题】:Eloquent - callback when model fetch is completeEloquent - 模型获取完成时的回调
【发布时间】:2015-10-14 00:58:25
【问题描述】:

我有一个模型“Page”,它具有一对多关系“PageCustomField”(就像 WordPress 的自定义字段概念)。

此自定义字段模型有两个字段,键和值。我想做的是能够在 Twig 模板中执行以下操作,其中 page 是父 Page 模型,custom 是自定义字段的集合,emailkey 查询自定义字段关系。输出将是 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();
    });
}

查看 Illuminate\Database\Eloquent\Model 方法,我看不到可以实现此目的的回调,但可以做到吗?我可以重写 firstOrFail() 方法,但宁愿不这样做。

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    我相信您可以在这种情况下使用accessor

    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
    

    【讨论】:

    • 这正是我正在寻找的东西,但问题是自定义字段数据仍然存在关系 - 我目前必须执行$page->customFields()->where('key', 'email')->first()->value 之类的操作才能获得结果。我想要做的是调用$page->customFields->email 以获取带有键“电子邮件”的自定义字段的值。我只是想简化将自定义字段提取到一个数组或对象中,该数组或对象可通过父对象直接访问,而无需子查询。
    • 其实你是对的——可以这样实现。以上已更新 - 谢谢!
    猜你喜欢
    • 2015-07-26
    • 2023-03-16
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    相关资源
    最近更新 更多