Laravel:PHP特性可以向模型的受保护值添加值

我正在使用Laravel 7,目前正在尝试通过使用PHP特性集中一些代码。但是,我想拥有例如还将值添加到protected $attributes变量或protected $with变量中。

我为什么要那样?因为我想重复使用代码,而不是告诉每个Laravel模型在哪里使用我的特征来加载关系并将属性添加到模型中。那将是多余的...

我已经想出了一种向protected $attributes变量添加值的方法。但是,如何将comments添加到我的protected $with变量中?

这是将值添加到protected $attributes变量的代码:

    /* Add attributes to model $appends */
    protected function getarrayableAppends()
    {
        $this->appends = array_unique(array_merge($this->appends,['publishedComments']));

        return parent::getarrayableAppends();
    }

亲切的问候

iCMS 回答:Laravel:PHP特性可以向模型的受保护值添加值

模型所使用的特性可以被“引导”和“初始化”。引导通常是一种调整行为的静态方法。初始化是在模型的每个新实例上完成的,这就是您想使用的:

protected function initializeYourTraitName()
{
    // do what you need to merge into $this->appends
    // do what you need to merge in new values to $this->with
}

如果您检查Illuminate\Database\Eloquent\Model的构造函数,则会看到对initializeTraits的调用。

您还需要定义一种启动特征的方法,该方法将使模型意识到应该在模型的每个新实例上调用的“初始化”方法。

protected static function bootYourTraitName()
{
    $class = static::class;
    $method = "initializeYourTraitName";

    static::$traitInitializers[$class][] = $method;

    static::$traitInitializers[$class] = array_unique(
        static::$traitInitializers[$class]
    );
}

这些是你特质的方法。

您必须将YourTraitName部分更改为特征的名称。

本文链接:https://www.f2er.com/1521992.html

大家都在问