douhuan3448 2015-11-25 03:37
浏览 45

使用Laravel Eloquent插入数组

I have an array which I combined using array_combine. I am trying to store each array KEY AND VALUE into a child table. However, I can't figure out to do this. Please help!

HERE'S AN EXAMPLE OF A RETURNED ARRAY array:2 [▼ "Design" => "Pattern" "Brand" => "Sony" ]

PRODUCT MODEL

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

PRODUCT ATTRIBUTE MODEL

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

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

PRODUCT CONTROLLER

$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);
    }

When I run this, I get one row inserted into the product table, and one row inserted into the product_attribute table. However, the columns attribute_name and attribute_value is blank.

  • 写回答

1条回答 默认 最新

  • douluokuang7184 2015-11-25 06:22
    关注
    $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, ]);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度