简体   繁体   English

Doctrine DQL - 逻辑检查选择

[英]Doctrine DQL - Logic check in select

I am trying to use a LIKE comparison in a doctrine DQL in a MySQL database.我试图在 MySQL 数据库的学说 DQL 中使用 LIKE 比较。 It works directly in SQL in the database and looks like this:它直接在数据库中的 SQL 中工作,如下所示:

SELECT *, (name LIKE '%testO%') as partOfName
from organization
ORDER BY partOfName DESC;

This works just fine.这工作得很好。

Now I try to implement this logic in Doctrine.现在我尝试在 Doctrine 中实现这个逻辑。 My Querybuilder looks like this:我的 Querybuilder 看起来像这样:

oQueryBuilder
  ->from(OrganizationEntity::class, organization)
  ->select('organization')
  ->addSelect('(organization.name LIKE %:searchTerm%) AS searchTermIsPartOfName')
  ->setParameter('searchTerm', $sSearchTerm)
  ->orderBy('searchTermIsPartOfName', 'DESC')
;

Trying to run it or get the SQL out of it gives me the following error:尝试运行它或从中获取 SQL 给了我以下错误:

[Syntax Error] line 0, col 97: Error: Expected Doctrine\\ORM\\Query\\Lexer::T_CLOSE_PARENTHESIS, got 'LIKE' [语法错误] line 0, col 97: Error: Expected Doctrine\\ORM\\Query\\Lexer::T_CLOSE_PARENTHESIS, got 'LIKE'

It is definitely the part about the LIKE.这绝对是关于 LIKE 的部分。 I commented the last three lines out and it works.我把最后三行注释掉了,它起作用了。

How do I translate the above working SQL into Doctrine DQL?如何将上述工作 SQL 转换为 Doctrine DQL?

LIKE expressions are covered under Conditional Expressions in DQL's grammar. LIKE表达式包含在 DQL 语法中的条件表达式中。 And unfortunately, it's not possible to use these directly within a SelectExpression .不幸的是,不可能在SelectExpression直接使用这些。

However you can use them within a CaseExpression , which can be used in a SelectExpression , and replicate the same behaviour:但是,您可以在CaseExpression使用它们,它可以SelectExpression ,并复制相同的行为:

->addSelect('CASE WHEN (organization.name LIKE :searchTerm) THEN 1 ELSE 0 END AS searchTermIsPartOfName')
->setParameter('searchTerm', "%{$sSearchTerm}%")

(there was also a minor issue about your LIKE expression - I'm pretty sure the % signs need to be part of the parameter value, not the query itself) (还有一个关于你的LIKE表达式的小问题 - 我很确定%符号需要成为参数值的一部分,而不是查询本身)

you forgot '' after LIKE, replace with string你在 LIKE 之后忘记了'' ,用字符串替换

->addSelect('(organization.name LIKE %:searchTerm%) AS searchTermIsPartOfName')

on

->addSelect('(organization.name LIKE \'%:searchTerm%\') AS searchTermIsPartOfName')

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

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