php - JSON in longtext in mariabd returns "Could not convert database value to Doctrine type json"
Get the solution ↓↓↓Symfony 5, I write myUser
entity code accordingly with:
https://symfony.com/doc/current/security.html#denying-access-roles-and-other-authorization
and I use mariadb
public function getRoles(): array
{
$roles[] = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
and I added manually an user with roleROLE_ADMIN
.
I don't understand why it returns the error:
Could not convert database value "ROLE_ADMIN" to Doctrine Type json
Answer
Solution:
You get that error because you are setting the value to something that's an invalid JSON. If you are going to modify your DB directly, you should put a valid value for a JSON type. In this case it would be something like:
["ROLE_ADMIN"]
instead of:
ROLE_ADMIN
Additionally, you picked the incorrect column type. WhileJSON
is an alias forLONGTEXT
on MariaDb, onJSON
typed columns a constraint is added. As explained in the docs you linked:
In order to ensure that a a valid json document is inserted, the JSON_VALID function can be used as a CHECK constraint. This constraint is automatically included for types using the JSON alias from MariaDB 10.4.3.
This would have alerted you that the data you had entered manually was not a valid JSON document.
There is absolutely no need of changing the defaultgetRoles()
method you show. That one would work perfectly fine, if you are using a JSON type for the property as the error shows.
Answer
Solution:
As I wrote, I use MariaDB. On MariaDB help, we can read : look https://mariadb.com/kb/en/json-data-type/
So I try to replace in my entity (src/Entity/User.php)
public function getRoles(): array
{
$roles[] = json_encode($this->roles);
…
but it is a bad way as @yivi wrote, the first error is at value in db :
be careful also if you define manually, like me, an user in database, that you enter for example["ROLE_ADMIN"]
an notROLE_ADMIN
which could returns an other errorNotice: Array to string conversion
because I have a second error :
$roles[] = $this->roles;
//instead of
$roles = $this->roles;
Stupid typing error
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: using $this when not in object context
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.