1

I have a json column named Data in my user table in the database.

Example of content:

[
{
    "id": 10,
    "key": "mail",
    "type": "male", 
}, 
{
    "id": 5,
    "key": "name",
    "type": "female",
}, 
{
    "id": 8,
    "key": "mail",
    "type": "female",
}
]

let's assume that many row in the table may have the same content so they should be removed from all of the rows of the table too what i want to do is remove an item by key and value last thing i can come up with is this query for example i want to remove the item where id equal 10:

     UPDATE
      user
    SET
      `Data` =
 JSON_REMOVE(`Data`,JSON_SEARCH(`Data`,'all',10,NULL,'$[*].id'),10)

but this query remove the all the content of the column.

If any one could help this is much appreciated.

By the way i get on this way because i can't seem to find a way to make it using QueryBuilder in laravel So it will be RawQuery.

Thank you Guys

4

2 回答 2

2

经过大量的人工阅读和审讯后,我找到了答案,我将发布为有需要的人提供进一步帮助

 UPDATE
  user
SET
  `Data` = JSON_REMOVE(
    `Data`,
    REPLACE(
    REPLACE
      (
        JSON_SEARCH(
          Data,
          'all',
          '10',
          NULL,
          '$**.id'
        ),
        '.id',
        ''
      ),
        '"',
        ''
  )
  )

==> 当我多次搜索和更新查询和内容本身时的一些解释

我注意到 JSON_SEARCH 仅适用于字符串值,如果值为 int 它不会找到它,所以我将 id 的 id(s) 值转换为字符串,之后 JSON_SEARCH 将返回类似的内容,$[the searched key].id但因为我需要获取我需要修改洞项目,".id"所以替换内是为了这个目的,最后从结果中删除引号,因为它会像这样,"$[0]"但是 JSON_REMOVE 希望它是这样$[0]的,所以这就是第二次替换的目的,最后是它self 将被删除,数据将被更新

希望 laravel 团队将来可以支持这些事情,因为我搜索了很长时间,但不幸的是没有太多帮助,但我们可以通过原始声明完成。

==> 请注意,如果您搜索的项目在 JSON 内容中不存在,则所有 JSON 内容都将设置为 NULL

于 2018-08-04T17:43:15.807 回答
0

这是 Laravel 的方式:

$jsonString = '[{
        "id": 10,
        "key": "mail",
        "type": "male"
    },
    {
        "id": 5,
        "key": "name",
        "type": "female"
    },
    {
        "id": 8,
        "key": "mail",
        "type": "female"
    }
]';

// decode json string to array
$data = json_decode($jsonString);

// remove item that id = 10
$data = array_filter($data, function ($item) {
    return $item->id != 10;
});

// run the query
foreach ($data as $item){
    DB::table('user')->where('id', $item->id)->update($item);
}
于 2018-08-04T04:19:36.150 回答