szerz
szerz

Reputation: 257

How to add JSON field in DB?

I have some JSON field type in DB (manually added):

{"0": "ROLE_USER"}

The model of User:

/**
 * @ORM\Column(type="json")
 */
private $roles = [];

The Controller:

$user->setRoles(array('{"0": "ROLE_USER"}'));

It works adding data to DB:

["{\"0\": \"ROLE_USER\"}"]

If I add it with no array - there is an error:

Argument 1 passed to App\Entity\User::setRoles()
must be of the type array, string given

What should I do to have exactly {"0": "ROLE_USER"} in DB?

Upvotes: 2

Views: 12526

Answers (2)

AlterPHP
AlterPHP

Reputation: 12727

If you use Doctrine as ORM, you should use existing json mapping type that stores array as JSON string and automatically (de)serialize data.

Upvotes: 0

Thomas Baier
Thomas Baier

Reputation: 454

Change

$user->setRoles(array('{"0": "ROLE_USER"}'));

To

$user->setRoles(["ROLE_USER"]);

That will do the job.


Your array declaration is wrong. You push ONE Item to the array and the item is: {"0": "ROLE_USER"} as a plain string.

For a doctrine "json" column you dont need to json_encode or json_decode yourself. Doctrine will handle that for you!

The Flow:
1) You give Doctrine a array
2) Doctrine will json_encode your array and save it in the column as json_data
3) If you request the column value, doctrine will json_decode your array so you can work with your array again.


Your desired goal is also not correct. You want json_data like this:

{"0": "ROLE_USER"}

But i think you will have data like this:

{"ROLE_USER"}

But both cases would leed to the same array:

array {
  0 => ROLE_USER  
}

Upvotes: 4

Related Questions