1

I need to create a raw query in the repository class, but i'm geting and error

class UserRepository extends EntityRepository
{
   public function usertoExpirate(){

     $query = 'SELECT email 
     FROM user 
     WHERE type NOT IN("deleted", "admin") 
     AND  expiration_date < DATE_ADD(NOW(),INTERVAL -3 MONTH)';
    
     $statement = $this->getConnection()->prepare($query);
     $statement->execute();
     $user_to_expirate_password = $statement->fetchAll();

     return $user_to_expirate_password;
}

I'm getting this error

Undefined method 'getConnection'. The method name must start with either findBy, findOneBy or countBy!
1
  • 1
    Well let's see. The undefined method error message strongly implies the class does not have a method with that particular name. You might be a bit confused with the find stuff but that is because the repository class actually lets you do stuff like findByType without adding the actual method. It's just a distraction really. So how can you get a connection? Turns out EntityManager::getConnection exists. I'll leave it as an exercise in reading code for you to determine how to get the entity manager from a repository. Commented Dec 28, 2021 at 17:17

1 Answer 1

1

According to the documentation of Symfony 3.4 you need to get the entity manager, not the connection. Try it like this:

class UserRepository extends EntityRepository {
    public function usertoExpirate() {

        $query = 'SELECT email 
        FROM user 
        WHERE type NOT IN("deleted", "admin") 
        AND expiration_date < DATE_ADD(NOW(),INTERVAL -3 MONTH)';
   
        return $this->getEntityManager()
            ->createQuery($query)
            ->getResult();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Right idea as far as getting the entity manager but your code is mixing up SQL and DQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.