$ casts,数组数据

时间:2016-09-22 17:11:37

标签: php laravel laravel-5.2

我使用$ casts将数组中的数据保存到数据库中。我有一个问题。

如何将数据推送到数据库中的现有数组? 例如,我的db列中已经有一个数据数组,如:IContainer等等,在Controller中,我想在db中将这个数组中的一些其他数据从输入中推入。

IContainer container = builder.Build(); 

container.ComponentRegistry.RegistrationFor(new TypedService(typeof(IXService));

推送这样的数据。

2 个答案:

答案 0 :(得分:2)

你不能用Eloquent的质量分配功能(更新,创建等)来做到这一点。你必须拉下你的领域,改变它,然后保存模型。

$collection = collect($brand->field);
$collection->push($myNewData);
$brand->field = $collection->toJson();
$brand->save();

答案 1 :(得分:0)

方式1

    $brand = Brand::find($request->input('brand'));

    $brand->model = array_merge($brand->model, [$request->input('model')]);
    $brand->update();

方式2 (我最喜欢的,因为它封装了逻辑)

    $brand = Brand::find($request->input('brand'));

    $brand->addModel($request->input('model'));
    $brand->update();

在实体上:

    public function addModel($value)
    {
            $this->model = array_merge($this->model, [$value]);
    }

<强>可选

在实体上(而不是$casts):

    public function setModelAttribute($value)
    {
            $this->attributes['model'] = json_encode($value);
    }

    public function getModelAttribute($value)
    {
            return json_decode($value, true);
    }