php 如何访问 symfony 存储库中的创建查询方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11734147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:58:07  来源:igfitidea点击:

How to access create query method in symfony repository

phpsymfonydoctrine-orm

提问by Mirage

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!

未定义的方法“createQuery”。方法名称必须以 findBy 或 findOneBy 开头!

回答by Vitalii Zurian

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();

回答by Cosmtar

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

我知道这个答案已经很晚了,但是您的 userRepository 类需要在您的 User 实体中定义。

use Doctrine\ORM\Mapping as ORM
/**
 * @ORM\Entity(repositoryClass="NameOfBundle\Repository\UserRepository")
class User
{
    ...
}

回答by Mohammad Fareed

When we work at Repositories

当我们在 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

阅读更多

回答by jjoselon

The method CreateQueryis of Entity Manager, is not Controller's class

该方法CreateQuery实体管理器的,不是Controller的类