繁体   English   中英

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

[英]How to extend PHP Laravel model's fillable fields in a child class?

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

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

原厂model:

<?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
}

正如我想象的如何扩展原来的 model:

<?php
namespace App;

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

    // ...
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM