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

问题描述 投票:0回答:1

我尝试将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数组吗?

php laravel laravel-6 php-7.1 laravel-models
1个回答
0
投票

在子类构造函数中,您可以使用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']);
    }
© www.soinside.com 2019 - 2024. All rights reserved.