繁体   English   中英

在Laravel中的MySQL中插入JSON对象

[英]Inserting JSON object in MySQL in Laravel

我正在努力在JSON-type MySQL column插入JSON object

我尝试插入的示例数据如下所示:

样本数据

示例Laravel代码

public function store(Request $request)
{
    $layaway = new Layaway;

    foreach($request->selected_products as $p) {
        $layaway->selected_products = json_encode([
            'id' => $p['id'],
            'sku' => $p['sku'],
            'name' => $p['name'],
            'image' => $p['image'],
            'description' => $p['description'],
            'category_id' => $p['category_id'],
            'regular_price' => $p['regular_price']
        ]);

    }

    $layaway->save();

    return response()->json([
        'success' => true,
        'message' => 'Layaway Program has been successfully saved!'
    ]);

}

来自dd()的样本响应

样本结果

问题如何将$request->selected_products中的所有数据保存到MYSQL json-type column

如Wreigh的评论所述,

我只是更改了这段代码:

foreach($request->selected_products as $p) {
    $layaway->selected_products = json_encode([
        'id' => $p['id'],
        'sku' => $p['sku'],
        'name' => $p['name'],
        'image' => $p['image'],
        'description' => $p['description'],
        'category_id' => $p['category_id'],
        'regular_price' => $p['regular_price']
    ]);

}

变成这段代码:

$layaway->selected_products = json_encode($request->selected_products);

谢谢。

暂无
暂无

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

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