php - 如何在子类中扩展 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
我可以在子类中扩展我的原始模型数组吗?
解决方案
在您的子类构造函数中,您可以使用mergeFillable
来自Illuminate\Database\Eloquent\Concerns\GuardsAttributes
trait 的方法(自动适用于每个 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']);
}
推荐阅读
- scheme - 我可以使用附加!在文字列表上?
- python - AttributeError: 'str' 对象在噪声 = np.random.normal(0, 20, file_name.shape) 处没有属性 'shape'
- javascript - Javascript Excel Javascript API 脚本实验室中使用的 Danfo.js 库
- typescript - vuejs - v-model 不更新类属性
- javascript - 如何在 react native 中设置 redux?
- r - 用 0 按组替换前导 NA,但保留其他 NA
- java - 你好!将 ImageIcon 设置为 Jframe 和其他组件似乎不起作用。我需要帮助
- arrays - 显示来自 json 文件的对象
- c# - 有没有办法在 MVC Webgrid 的列标题上显示鼠标?
- javascript - .map() 未定义为函数