Apigility + Doctrine2 QueryProvider - 不能在查询生成器上使用创建的函数

Apigility + Doctrine2 QueryProvider - Can't use created function on query builder

我正在使用 Apigility 创建一个休息应用程序,其中后端和前端几乎是独立的应用程序。

好的,在后端我使用 'zf-apigility-doctrine-query-provider' 根据通过 url 发送的参数创建查询(即 localhost?instancia=10),但我需要处理信息使用 MS SQL 数据库存储函数,如下所示:

function createQuery(ResourceEvent $event, $entityClass, $parameters){

    /* @var $queryBuilder \Doctrine\ORM\QueryBuilder */
    $queryBuilder = parent::createQuery($event,$entityClass, $parameters);

    if (!empty($parameters['instancia'])) {

        $queryBuilder->andWhere($queryBuilder->expr()->eq('chapa.instancia', 'dbo.isItSpecial(:instancia)'))
        ->setParameter('instancia', $parameters['instancia']);
    }

    return $queryBuilder;        
}

但是它根本行不通,它不会接受 'dbo.isItSpecial' 并且我似乎无法访问 ServiceLocator,也无法访问 EntityManager 或除Querybuilder.

我想创建一个本机查询来获取结果并在主查询中使用它,但我似乎无法创建它。

有什么想法吗?

这个方法在什么地方class?为您的问题添加一些上下文。

你做了 parent::createQuery 这表明你在 a DoctrineResource instance. If this is true it means that both the ServiceLocator and the ObjectManager 中只是可用 class.

您可以阅读有关在 Doctrine 中执行本机查询的内容 here in the Documentation:

$rsm = new ResultSetMapping();

$query = $entityManager->createNativeQuery(
    'SELECT id, name, discr FROM users WHERE name = ?', 
    $rsm
);
$query->setParameter(1, 'romanb');
$users = $query->getResult();

原来我找到了一些方法。

方法是class,扩展了这个class

ZF\Apigility\Doctrine\Server\Query\Provider\DefaultOrm

这意味着我可以访问 ObjectManager。文档没有多大帮助,但 ObjectManager 实际上是一个 EntityManager(ObjectManager 只是接口),为了发现这一点,我不得不使用 get_class PHP 命令。

有了实体管理器,我可以完成威尔特建议的事情,像这样:

        $sqlNativa = $this->getObjectManager()->createNativeQuery("Select dbo.isItSpecial(:codInstancia) as codEleicao", $rsm);

然而,我创建了一个执行这个功能的服务(它会在很多地方使用),所以我也制作了一个将这个服务设置为查询提供者的工厂class,在配置文件上它是像这样。

    'zf-apigility-doctrine-query-provider' => array(
    'factories' => array(
        'instanciaDefaultQuery' => 'Api\Instancia\instanciaQueryFactory',
    ),
),

工厂看起来像这样(服务像 Wilt 的响应一样执行 NativeQuery):

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Api\EleitoChapaOrgao\EleitoChapaOrgaoQuery;

class InstanciaQueryFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceManager){
        $instanciaService = $serviceManager->getServiceLocator()->get('Application\Service\Instancia');

        $query = new InstanciaQuery($instanciaService);

        return $query;
    }
}

最后只需将构造函数添加到 QueryProvider,服务就可以在那里使用了:

class InstanciaQuery extends DefaultOrm
{    
    protected $instanciaService;

    public function __construct(Instancia $instanciaService)
    {
        $this->instanciaService = $instanciaService;
    }

    public function createQuery(ResourceEvent $event, $entityClass, $parameters)    
    { /* The rest of the code goes here*/