Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access create query method in symfony repository

I have the class user repository

class userRepository extends EntityRepository
{

    function getuserData($id)
    {
        $query = $this->createQuery('
                SELECT c FROM AcmeBundle:User c 
                WHERE c.id = :id ORDER BY c.id ASC
            ')
            ->setParameter('id', $id);

        return $query->getResult();
    }
}

I am getting this error

Undefined method 'createQuery'. The method name must start with either findBy or findOneBy!

like image 603
Mirage Avatar asked Jul 31 '12 06:07

Mirage


3 Answers

According to docs

$em = $this->getEntityManager();
$query = $em->createQuery('
        SELECT p FROM AcmeStoreBundle:Product p 
        WHERE p.price > :price 
        ORDER BY p.price ASC
    ')
    ->setParameter('price', '19.99');

$products = $query->getResult();
like image 158
Vitalii Zurian Avatar answered Nov 15 '22 07:11

Vitalii Zurian


I know this answer is quite late but your userRepository class needs to be defined in your User entity.

use Doctrine\ORM\Mapping as ORM
/**
 * @ORM\Entity(repositoryClass="NameOfBundle\Repository\UserRepository")
class User
{
    ...
}
like image 29
Cosmtar Avatar answered Nov 15 '22 08:11

Cosmtar


When we work at Repositories

$em = $this->getEntityManager(); //wont work in repository
$em->createQueryBuilder($sql); 

you have to use

$conn = $this->getEntityManager()->getConnection();     
$stmt = $conn->prepare($sql);

Read More

like image 1
Mohammad Fareed Avatar answered Nov 15 '22 09:11

Mohammad Fareed