简体   繁体   English

在Phalcon Framework中不存在与Phql一起使用

[英]Using not exists with Phql in Phalcon Framework

I'm trying to write a short query with phql . 我正在尝试使用phql编写简短查询。 I'm selecting everything from one table and have a where clause declaring that another table can't have a record connected to this table. 我正在从一个表中选择所有内容,并具有一个where子句,该语句声明另一个表无法将记录连接到该表。 Here's the raw sql query that works fine when run against my db, which is Mysql. 这是对我的数据库Mysql运行时可以正常工作的原始sql查询。

select * from application a
where not exists (select distinct 1 from preapproval p where p.application_id = a.id)

So on to trying to write this in phql , I've been trying different things, but here's what I've ended up with. 因此,在尝试用phql编写代码时 ,我一直在尝试其他事情,但这就是我最终得到的结果。

Note: If I run this without the where clause it works, selecting all records from the 'application' table. 注意:如果我在没有where子句的情况下运行此命令,请从“应用程序”表中选择所有记录。

$manager = \Phalcon\DI::getDefault()->getShared("modelsManager");

$data = $manager
    ->createBuilder()
    ->from(['a' => '\Models\Application'])
    ->where('not exists (select distinct 1 from [\Models\Preapproval] where [\Models\Preapproval].application_id = a.id)')
    ->getQuery()
    ->execute();

The exception being thrown is: 抛出的异常是:

Syntax error, unexpected token SELECT, near to ' distinct 1 from [\Models\Preapproval] where [\Models\Preapproval].application_id = a.id)', when parsing: SELECT [a].* FROM [\Models\Application] AS [a] WHERE not exists (select distinct 1 from [\Models\Preapproval] where [\Models\Preapproval].application_id = a.id) (190)

So on to the question, how do I write a where not exists clause in phql ? 那么关于这个问题, 我怎么在phql中写一个where不存在子句呢?

Unfortunately Phalcon is not always able to parse complex queries using PhQL query builder. 不幸的是,Phalcon并不总是能够使用PhQL查询构建器来解析复杂的查询。

However in this particular case you can do a leftJoin with condition: 但是,在这种特殊情况下,您可以使用条件执行leftJoin:

/** @var ModelManager $manager */
$manager = \Phalcon\DI::getDefault()->getShared("modelsManager");
$data = $manager->createBuilder()
    ->columns('\Models\Application.*')
    ->from('\Models\Application')
    ->leftJoin('\Models\Preapproval', '\Models\Preapproval.application_id = \Models\Application.id')
    ->andWhere('\Models\Preapproval.id IS NULL')
    ->getQuery()
    ->execute();

This may or may not have a negative or positive impact on performance depending on your database index cardinality. 根据您的数据库索引基数,这可能会对性能产生负面影响或没有正面影响。

I had a similar problem. 我有一个类似的问题。 You can either use raw sql , left joins (in my case i had to use many 'join ON' conditions) or you can try this 您可以使用原始sql ,左连接(在我的情况下,我必须使用许多“ join ON”条件),也可以尝试使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM