如何使用Laravel / Eloquent操纵JSONB字段中的对象数组?

时间:2020-11-09 23:15:26

标签: json laravel eloquent

我的数据库的destination_data字段中有这种JSONB对象:

[
    {
        "uuid": "20670fe3-eb4a-4097-b29c-78b4b5a7ffc0",
        "name": "foo",
        "address" bar,
    },
    {
        "uuid": "20424d4f-7ffd-4fd2-a434-74f318385ccf",
        "name": "foo",
        "address" bar,
    },
    {
        "uuid": "eb5e12b3-25bb-43a5-9e8e-02ebc0831edf",
        "name": "foo",
        "address" bar,
    },
    {
        "uuid": "78600c45-18b7-4eb8-8f5c-403296bd1635",
        "name": "foo",
        "address" bar,
    },
    {
        "uuid": "f96f5751-d984-435e-9361-14c767ce312d",
        "name": "foo",
        "address" bar,
    }
]

我知道Eloquent可以像这样直接访问jsonb字段:

$affected = DB::table('users')
              ->where('id', 1)
              ->update(['options->enabled' => true]);

但是,如果我需要通过其uuid更新json对象并更改name等怎么办?基本上是克隆整个对象并使用Eloqeunt更新整个字段吗?像这样:

$destinationData = $myModel->destination_data;
$keyOfFirstDestination = array_search('20670fe3-eb4a-4097-b29c-78b4b5a7ffc0', $destinationData);
$firstDestination = destinationData[$keyOfFirstDestination);
[..blah blah blah]

肯定有更简单的方法吗?

0 个答案:

没有答案