首页 > 解决方案 > 如何在子类中扩展 PHP Laravel 模型的可填充字段?

问题描述

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

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

原型号:

<?php
namespace App;

use App\Scopes\VersionControlScope;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'product_id',
        'name',
        'unit',
        // ...
    }

    // ... relations, custom complex functions are here
}

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

<?php
namespace App;

class ProductBackup extends Product
{
    protected $fillable = array_merge(
        parent::$fillable,
        [
            'date_of_backup',
        ]
    );

    // ...
}

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

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

标签: phplaravellaravel-6php-7.1laravel-models

解决方案


在您的子类构造函数中,您可以使用mergeFillable来自Illuminate\Database\Eloquent\Concerns\GuardsAttributestrait 的方法(自动适用于每个 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']);
    }

推荐阅读