【发布时间】:2017-06-22 14:33:43
【问题描述】:
所以我有一个Page 模型,它扩展了Eloquent Model 类。我正在尝试覆盖构造函数,我需要一些额外的逻辑。这是我目前拥有的:
class Page extends Model
{
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->main_image = null;
}
}
但是当我调用Page::find(1); 时,这似乎不会将main_image 保存到$this->attributes 属性中。
我相信这是因为Page::find 最终会调用Model::newFromBuilder,看起来像这样:
public function newFromBuilder($attributes = [], $connection = null)
{
$model = $this->newInstance([], true);
$model->setRawAttributes((array) $attributes, true);
$model->setConnection($connection ?: $this->getConnectionName());
return $model;
}
如您所见,它首先创建实例,然后设置属性,这意味着在构造函数中设置的任何内容都会被忽略。
是否有任何解决方法可以覆盖构造函数(或类似方法)以更改每个检索/创建的模型实例的属性?显然我可以覆盖newFromBuilder、newInstance、__construct 和类似的方法,但这似乎非常hacky 和不可维护。
谢谢!
【问题讨论】:
-
所以基本上你想在创建新元素时覆盖一个参数?您应该为此使用模型事件,laravel.com/docs/5.4/eloquent#events - 特别是查看“创建/创建”。
-
覆盖只是一个例子,可能有多个参数覆盖,它们将被包裹在 if 语句等中。我将检查事件,如果我可以将它们应用于所有类而无需编写观察者我拥有的每个模型的课程。谢谢!
-
您的模型没有
main_image字段是否有原因?将其设置在模型中的最终目标是什么?可能有另一种解决问题的方法可能会提供更多信息,如果所有页面都有main_image,则可能会形成关系,以便您可以执行$page->mainImage->get() -
这背后的原因是另一个问题的潜在解决方案:stackoverflow.com/questions/44699673/…所以我想检查
$page->main_image_id是否为空,将$page->main_image设置为null并且不调用关系方法