【问题标题】:Storing multiple array values as a JSON column in Laravel在 Laravel 中将多个数组值存储为 JSON 列
【发布时间】:2019-07-25 03:17:27
【问题描述】:

我正在尝试将一组具有相同名称的字段中的表单值存储到JSON 列类型中。


<?php
//Form values as an array
$title = request('title');
$price = request('price');
$link = request('link');

 $arrM = array();

 for($i = 0; $i < count($title); $i++) {
    $arrM[] = array(
       'title' => $title[$I], 
       'price' => $price[$I],
       'link' => $link[$i],    
    );
 }

 Tag::create([
  'title' => request('title'),
  'tag_points' => $arrM,
 ]);

我已获取每个值并组合成一个数组并将强制转换设置为array。 Laravel 将不接受以下格式

$arrM - 输出

array:2 [▼
  0 => array:3 [▼
    "title" => "First Title"
    "price" => "10"
    "link" => "https://google.com"
  ]
  1 => array:3 [▼
    "title" => "Second Title"
    "price" => "40"
    "link" => "https://stackoverflow.com"
  ]
]

错误

Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given

我希望它如何存储在 DB 列中

[{
    "title": "First Title",
    "price": "10",
    "link": "https://google.com"
}, {
    "title": "Second Title",
    "price": "40",
    "link": "https://stackoverflow.com"
}]

【问题讨论】:

  • 我发现了问题 - 我在测试帖子标题时使用了相同的 title 字段,导致在字符串字段中输入了多个值!

标签: php arrays laravel eloquent


【解决方案1】:

要在迁移中存储 JSON 字段,您必须执行以下操作:

$table->json('field')

然后,如果您想获取这些值,则必须将此值从 JSON 转换为 Array。您可以使用 $casts 属性来做到这一点。

class YourModel extends Model
{
    protected $casts = [
        'field' => 'array'
    ];
}

【讨论】:

  • 嘿! - 恐怕我已经设置了这些。问题是它没有与当前代码一起存储。
猜你喜欢
  • 2019-05-01
  • 2020-09-05
  • 2014-05-16
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多