首页 > 解决方案 > Laravel eloquent - 合并父级 $appends

问题描述

假设我有两个模型,Veichle并且Car.

Veichle extends Model {
    $appends = ['append_1', 'append_2'];
}

Car extends Veichle {
    $appends = ['append_3', 'append_4'];
}

append_1如果我有 Car 对象,我该如何使用?这样 Car 类只是覆盖了父 $appends,我没有找到任何方法来合并它

标签: laraveleloquent

解决方案


您可以使用该append方法在构造函数中执行此操作,因为它将提供的属性附加到现有属性:

Car extends Vehicle
{
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->append(['append_3', 'append_4']);
    }
}

推荐阅读