如何在子类中扩展 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我可以在子类中以某种方式扩展原始模型的数组吗?


月关宝盒
浏览 106回答 1
1回答

ITMISS

在你的子类构造函数中,你可以使用mergeFillable来自 trait 的方法Illuminate\Database\Eloquent\Concerns\GuardsAttributes(自动适用于每个 Eloquent 模型)。/**&nbsp; &nbsp; &nbsp;* Create a new Eloquent model instance.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param&nbsp; array&nbsp; $attributes&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function __construct(array $attributes = [])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; parent::__construct($attributes);&nbsp; &nbsp; &nbsp; &nbsp; $this->mergeFillable(['date_of_backup']);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP