繁体   English   中英

使用Laravel Eloquent插入数组

[英]Inserting array using Laravel Eloquent

我有一个数组,我使用array_combine合并了。 我试图将每个数组的键和值存储到子表中。 但是,我不知道要这样做。 请帮忙!

这里是一个返回数组数组的示例:2 [▼“ Design” =>“ Pattern”“ Brand” =>“ Sony”]

产品型号

  public function productAttributes()
    {
        return $this->hasMany('App\ProductAttribute');
 }

产品属性模型

protected $fillable = [
    'attribute_name', 'attribute_value', 'used_as_filter'
];

public function product()
{
    return $this->belongsTo('App\Product');
}

产品控制器

$product = new Product();
    $product->category_id = $request->category_list;
    $product->name = $request->name;
    $product->price = $request->price;

    $product->save();

    /**Optional Data**/
    if ($request->has('attribute_name')){
        $attributes = array_combine($request->input('attribute_name'), $request->input('attribute_value'));

        $product->productAttributes()->create($attributes);
    }

运行此命令时,我将一行插入到product表中,并将一行插入到product_attribute表中。 但是,列attribute_name和attribute_value为空。

$attributes = array_combine($request->input('attribute_name'), $request->input('attribute_value'));

collect($attributes)->each(function ($value, $name) use ($product) {
    $product->productAttributes()->create([ 'attribute_name' => $name, 'attribute_value' => $value, ]);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM