【问题标题】:Just insert a new key - value on a mysql json field on Laravel只需在 Laravel 的 mysql json 字段上插入一个新的键值
【发布时间】:2020-09-21 01:46:31
【问题描述】:

我使用 Laravel 并尝试将条目添加到 JSON 格式的 MySQL 字段...

此字段包含(例如)以下内容:

        {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }

我的目标是:

            {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2",
                "image": "/url/to/img.jpg"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }

我的控制器是这样工作的:

$page = new Page();
        $page->contenu = $request->input('composants'); // Json field
        $page->save();

        foreach($page->contenu as $i => $element){
            if ( $request->hasFile("composants." . $i . ".image") ){
                $image =  $request->file("composants." . $i . ".image");
                // ... image processing, save on directory, etc... 
            }
        }

因此我想接手

的内容
$page->contenu

并为其添加“图像”的值,但我无法实现...

提前谢谢你:)

【问题讨论】:

标签: mysql json laravel


【解决方案1】:

这是一个您可以适应您的代码的示例:

$json = '{
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
}';

$arr = json_decode($json, true);
$arr['df2jay22p1f1nb31b161jf2jay22p5']['image'] = "/url/to/img.jpg";
$json = json_encode($arr);
echo '<pre>';
print_r(json_decode($json, true));
echo '</pre>';

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2018-12-19
    • 2017-04-26
    • 2015-04-03
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多