如何使用Laravel Eloquent ORM将数组值插入表中?

时间:2018-08-17 12:34:27

标签: mysql arrays laravel

下面是数组。我想通过Laravel雄辩的ORM系统将数组插入到我的“ sells”表中。但是

$data = [
                'products' => [
                    'product_id' => ['1', '3', '4'],
                    'quantity' => ['5', '5', '4'],
                    'product_discount' => ['30', '0', '5'],
                    'discount_unit' => ['%', 'tk', '%'],
                ],

                'customer_id' => 1,
                'total_discount' => 50,
                'shiping_charge' => 10,
                'net_payable' => 5000,

                'payments' => [
                    'payment_method' => ['cash', 'card', 'check'],
                    'payment_amount' => ['500', '7000', '400'],
                ],
            ];

这是将数据插入sells表的口才代码。

$ sell = new Sell();

    $sell->sells_code = 'SCN-' . rand(time(), 1000);

    $sell->sells_date = date('Y-m-d');

    foreach ($data['products']['product_id'] as $value){
        $sell->product_id = $value . ",";
    }



    foreach ($data['products']['quantity'] as $value){
        $sell->product_quantity = $value . ",";
    }

    foreach ($data['products']['product_discount'] as $value){
        $sell->product_discount = $value . ",";
    }

    foreach ($data['products']['discount_unit'] as $value){
        $sell->product_discount_unit = $value . ",";
    }


    $sell->customer_id = $data['customer_id'];
    $sell->company_name = 'Undefined';
    $sell->warehouse_id = 1;
    $sell->total_discount = $data['total_discount'];

    $sell->shipping_address = 'Undefined Address';
    $sell->shipping_charge = 0;
    $sell->net_payable = $data['net_payable'];


    foreach ($data['payments']['payment_method'] as $value){
        $sell->payment_method = $value . ",";
    }

    foreach ($data['payments']['payment_amount'] as $value){
        $sell->payment_amount = $value . ",";
    }


    $sell->payment_date= date('Y-m-d');
    $sell->note = 'Nothing';
    $sell->sells_Status = 'Success';
    $sell->biller = 'Mahady';


    $sell->save();

请您分享将数组值插入mysql数据库表的最有效方法吗?

1 个答案:

答案 0 :(得分:1)

第一件事不是要连接product_id,实际上是在每次迭代中将新值分配给$ sell-> product_id。

这可以帮助您

foreach ($data['products']['product_id'] as $value){
        $sell->product_id .= $value . ",";
}

或者您可以将此数组转换为json字符串,然后将其存储在表列中

$sell->product_id = json_encode($data['products']['product_id'])

然后从db检索,只需执行此操作,您将获得ID的数组

json_decode($sell->product_id)