Home » Php » php – Doctrine & Symfony – Get data from database with parameter on array column

php – Doctrine & Symfony – Get data from database with parameter on array column

Posted by: admin February 25, 2020 Leave a comment

Questions:

Good afternoon,

I try to find, from my database specific users with a role which is passed in parameter to the query. However, I have “null” result currently.

The users class is like this example from Symfony Documentation.

This is my CustomerRepository:

class CustomerRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Customer::class);
    }

    public function findByRole(string $role)
    {
        return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Customer c
              WHERE c.roles IN (:role)'
        )
            ->setParameter(':role', $role)
            ->getResult()
        ;
    } 
}

I expect to return an array which contains one or several users who have the role.

How to&Answers:

c.roles is a list that can contains multiple items (roles), so please can you reverse the where like this :

WHERE :role IN c.roles

PS: insure the case of string $role is upper (e.g “ROLE_ADMIN”).

Answer:

First of all in the class from the example you have given does not have declared variable called roles, therefore you cannot write this

 ... WHERE c.roles IN (:role)'

So in your User class you should have something like this

private $roles;

Also as it said here you can have “multiple tables and JOIN them
in your queries.”

So you would have 1 table for all your roles, one for the users and one called user_roles where you will store the roles for each user.
The next step I would approach is to search this new table for the user I want and then retrieve all rows containing the different roles in an array.

Also there are other ways – stated here. The method I recommend when storing arrays is to have a VARCHAR field (or TEXT) and then use (in your case) the Symfony serializer component to serialize() the array when saving in the DB and to deserialize()it when needed.

Answer:

Good evening,

Thx for your help.

To resolve this problem, I considered that a User have only one role in application, in this context, the solution is like this:

public function findByRole(string $role, int $isActive = 1): ?Customer
{
    return $this->getEntityManager()->createQuery(
            'SELECT c
             FROM App\Entity\Cutomer c
             WHERE c.roles LIKE :role
             AND c.isActive = :isActive'
        )
        ->setParameters([
             ':role' => '%'.$role.'%',
             ':isActive' => $isActive,
        ])
        ->getOneOrNullResult()
    ;
}