【问题标题】:Laravel - Extend Model $guarded from parent modelLaravel - 从父模型扩展模型 $guarded
【发布时间】:2020-09-24 16:37:32
【问题描述】:

我有一个扩展 Illuminate\Database\Eloquent\Model 的 BaseModel 类:

class BaseModel extends Model
{
    protected $guarded = ['id', 'company_id', 'identifier'];
}

在我的其他模型类中,我扩展了BaseModel,并尝试在子模型中从BaseModel 扩展$guarded:

class Person extends BaseModel
{
    public function __construct(array $attributes = array())
    {
        parent::__construct($attributes);
        $this->guarded = array_merge($this->guarded, ['address', 'phone']); //This is that I'm trying to do
    }
}

但是,它不起作用。是否可以从父模型扩展 $guarded 或者我也需要在子模型上声明所有字段?

解决方案 - 感谢@Jignesh Joisar!

public function __construct(array $attributes = array())
{
    $this->guard(array_merge($this->getGuarded(), ['address', 'phone']));
    parent::__construct($attributes);
}

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-6


    【解决方案1】:

    使用 baseModel 上已有的 GuardsAttributes 特征函数

    public function __construct(array $attributes = array())
    {
        $this->guard(array_merge($this->getGuarded(), ['address', 'phone']));
        parent::__construct($attributes);
    }
    

    【讨论】:

    • 您好!感谢您的帮助,它现在可以工作了,但就是这样:` $person = new Person(); $person->fill($request->all()); ` 但不是这样工作的: ` $person = new Person($request->all()); //这种方式只保持父级受保护`但我认为这是唯一的方法,因为它首先调用父构造函数,然后用$this->guard(...)..更改受保护
    • 更新:我刚刚更改了构造函数的顺序,首先调用$this->guard(),然后调用parent::__construct(),它成功了!非常感谢!
    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2020-06-19
    相关资源
    最近更新 更多