我正在使用 QueryBuilder 来获取 10 个最大的城市。
$query = $em->createQueryBuilder()
->select('c','s')
->from('CitiesBundle:Cities', 'c')
->innerJoin('c.state', 's','WITH', 'c.state = s')
->orderBy('c.population', 'DESC')
->setMaxResults(10)
->getQuery();
生成的 SQL:
SELECT c0_.id AS id0, c0_.name AS name1, c0_.landarea AS landarea2, c0_.density AS density3, c0_.population AS population4, s1_.id AS id5, s1_.name AS name6, c0_.state_id AS state_id7 FROM 城市c0_ INNER JOIN states s1_ ON c0_.state_id = s1_.id AND (c0_.state_id = s1_.id) ORDER BY c0_.population DESC LIMIT 10
当我在 PHPMyAdmin 中测试该查询时,每个城市都有自己的州,但在应用程序中,数组中的所有城市都与第一个城市的州相关联。
在这种情况下,有人可以为我解释 Doctrine2 的行为吗?
[编辑]
架构:
XYZ\Bundle\CitiesBundle\Entity\Cities:
type: entity
table: cities
fields:
#fields
oneToMany:
state:
targetEntity: States
cascade: { }
mappedBy: null
inversedBy: null
joinColumns:
state_id:
referencedColumnName: id
orphanRemoval: false
lifecycleCallbacks: { }
XYZ\Bundle\CitiesBundle\Entity\States:
type: entity
table: states
fields:
id:
id: true
type: boolean
nullable: false
generator:
strategy: IDENTITY
name:
type: string
length: 50
fixed: false
nullable: false
lifecycleCallbacks: { }
我尝试了不同的架构选项(ManyToOne 等)但没有运气
PHPMyAdmin、mazowieckie 等的屏幕截图是州名。在我的应用程序中,所有 10 个城市都有 state->name mazowieckie。
应用外观截图:
我在循环中输出州名:{{ city.state.name }}