Php 雄辩-模型获取完成时回调
我有一个模型“页面”,它有一个一对多关系“PageCustomField”(类似于自定义字段的WordPress概念) 此自定义字段模型有两个字段,键和值。我想做的是能够在细枝模板中执行以下操作,Php 雄辩-模型获取完成时回调,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我有一个模型“页面”,它有一个一对多关系“PageCustomField”(类似于自定义字段的WordPress概念) 此自定义字段模型有两个字段,键和值。我想做的是能够在细枝模板中执行以下操作,page是父页面模型,custom是自定义字段的集合,email是查询自定义字段关系的键。输出将是PageCustomField模型的值字段 {{ page.custom.email }} 我通过在页面模型中添加以下内容实现了这一点: public $custom = array(); public
page
是父页面模型,custom
是自定义字段的集合,email
是查询自定义字段关系的键。输出将是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();
});
}
通过illumb\Database\elount\Model方法,我看不到可以实现这一点的回调,但它可以实现吗?我可以重写
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
这是我正在寻找的,但问题是自定义字段数据仍然处于一种关系中-我当前必须执行类似于
$page->customFields()->where('key','email')->first()->value
的操作才能得到结果。我要做的是调用$page->customFields->email
,以获取带有键“email”的自定义字段的值。我只想简化将自定义字段提取到一个数组或对象中的过程,该数组或对象可以通过父级直接访问,而无需子查询。事实上,您是对的,可以通过这种方式实现。有更新以上-谢谢!