Home > Mobile >  Laravel Eloquent : How to remove json column children key?
Laravel Eloquent : How to remove json column children key?

Time:04-14

I have a jsonb column foo in which I would like to remove the key bar->abc without modifying other children keys.

I tried this:

MyModel::find(123)->update([
        'foo' => DB::raw("JSON_REMOVE(foo, 'bar->abc')")
    ]);

But it reseted the foo jsonb column to [].

How can I remove a given key like bar or only children key like bar->abc from a jsonb column with Laravel Eloquent?

(I'm using PostGreSQL database)

CodePudding user response:

I recommended you use $casts property in your model:

 protected $casts = [
    'foo'  => 'array',
];

to cast your column data to the array, then modify the result that is in the array format.

CodePudding user response:

I finally fixed it with:

DB::connection('myconnection')
  ->statement("UPDATE myschema.users 
               SET    foo = foo::jsonb - 'bar'
               WHERE  id  = '123';"
  );
  • Related