如何在子类中扩展 PHP Laravel 模型的可填充字段?

net*_*djw 7 php laravel php-7.1 laravel-6 laravel-models

我尝试使用其他一些字段扩展 extintig \xcb\x99PHP` Laravel 模型,但我没有找到正确的解决方案。我使用 PHP 7.1 和 Laravel 6.2

\n\n

这是我的代码,解释了我想要做什么。

\n\n

原型号:

\n\n
<?php\nnamespace App;\n\nuse App\\Scopes\\VersionControlScope;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Product extends Model\n{\n    protected $fillable = [\n        \'product_id\',\n        \'name\',\n        \'unit\',\n        // ...\n    }\n\n    // ... relations, custom complex functions are here\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如我想象的那样如何扩展原始模型:

\n\n
<?php\nnamespace App;\n\nclass ProductBackup extends Product\n{\n    protected $fillable = array_merge(\n        parent::$fillable,\n        [\n            \'date_of_backup\',\n        ]\n    );\n\n    // ...\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但现在我收到Constant expression contains invalid operations错误消息。

\n\n

$fillable我可以在子类中扩展显示原始模型的数组吗?

\n

Shi*_*n83 19

在子类构造函数中,您可以使用特征mergeFillable中的方法Illuminate\Database\Eloquent\Concerns\GuardsAttributes(自动适用于每个 Eloquent 模型)。

/**
     * Create a new Eloquent model instance.
     *
     * @param  array  $attributes
     * @return void
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->mergeFillable(['date_of_backup']);
    }
Run Code Online (Sandbox Code Playgroud)

  • 您想在父级构造函数之前调用 mergeFillable。默认构造函数调用“$this-&gt;fill($attributes)”。之后合并就太晚了,可填充的数据将会丢失。 (3认同)