我定义了2个实体:
我正在尝试选择州实体并自动加入城市实体,并按州名称对结果进行排序。但是,我收到了这个错误:
[Syntax Error] line 0, col 74: Error: Expected Literal, got 'BY'
我创建查询的代码是:
$statesQuery = $this->getEm()->createQueryBuilder();
$statesQuery->select("st");
$statesQuery->from("CoreBundle:State", "st");
$statesQuery->leftJoin("CoreBundle:City", "ct");
$statesQuery->addSelect("ct");
$statesQuery->orderBy("st.name", "ASC");
$statesQuery = $statesQuery->getQuery();
$states = $statesQuery->getResult();
如果我删除订单按方法,我会收到以下错误:
[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got end of string.
DQL生成的查询(带有顺序By和没有orderBy):
SELECT st, ct FROM CoreBundle:State st LEFT JOIN CoreBundle:City ct ORDER BY s.name ASC
SELECT st, ct FROM CoreBundle:State st LEFT JOIN CoreBundle:City ct
州实体:
Ec\CoreBundle\Entity\State:
type: entity
table: states
id:
id:
type: integer
nullable: false
unsigned: false
comment: ''
id: true
generator:
strategy: IDENTITY
fields:
name:
type: string
nullable: false
length: 255
friendly_url:
type: string
nullable: false
length: 255
oneToMany:
cities:
targetEntity: City
mappedBy: state
oneToOne:
country:
targetEntity: Country
lifecycleCallbacks: { }
城市实体:
Ec\CoreBundle\Entity\City:
type: entity
table: cities
id:
id:
type: integer
nullable: false
unsigned: false
comment: ''
id: true
generator:
strategy: IDENTITY
fields:
name:
type: string
nullable: false
length: 255
friendly_url:
type: string
nullable: false
length: 255
manyToOne:
state:
targetEntity: State
inversedBy: cities
lifecycleCallbacks: { }
答案 0 :(得分:0)
如果要检索状态集合(以及关联的城市),这就足够了:
// src/AcmeBundle/Controller/MyController.php
// ...
$statesQuery = $this->getDoctrine()->getManager()->createQueryBuilder();
$statesQuery->select("st")
->from("CoreBundle:State", "st")
->orderBy("st.name", "ASC");
$states = $statesQuery->getQuery()
->getResult();
所以城市将会延迟加载。有关延迟/急切加载的更多信息,请查看doctrine2 doc
修改强> 好吧,如果你只在一个地方需要这个,只需:
$statesQuery = $this->getDoctrine()->getManager()->createQueryBuilder();
$statesQuery->select("st, ct")
->from("CoreBundle:State", "st")
->leftJoin("st.cities", "ct")
->orderBy("st.name", "ASC");
$states = $statesQuery->getQuery()
->getResult();