【发布时间】:2015-12-03 19:53:18
【问题描述】:
我的表格如下:product_id->name,description,price
我想检索所有产品,所以这是我检索产品的代码
$doc = $this->getDoctrine();
$em = $doc->getEntityManager();
$conn = $em->getConnection();
$repo = $doc->getRepository('AppBundle:Products');
$query = $repo->createQueryBuilder('p')->getQuery();
$sql = $query->getSql();
$stmt = $conn->prepare($sql);
$stmt->execute();
$products = $stmt->fetchAll(\PDO::FETCH_ASSOC);
问题是在构建查询时,它总是在列名之后添加列索引后缀作为别名
所以结果会是这样的:
[
{"product_id_0":"1","name_1":"Name1","description_2":"Desc1","price_3":"100"},
{"product_id_0":"2","name_1":"Name2","description_2":"Desc2","price_3":"200"}
]
请注意,它们在列名之后是 _0、_1 之类的后缀,我不想要它, 如何构建没有这样别名的查询?
【问题讨论】:
-
用 $query->fetchArray 替换你的最后一行。更好的是,使用 fetchAll 并使用对象。 doctrine-orm.readthedocs.org/projects/doctrine-dbal/en/latest/…
-
@Cerad 它们在 Doctrine\ORM\Query 和 Doctrine\DBAL\Statement 类中没有名为 fetchArray 的方法。
-
我打字太快了。 $查询->getArrayResult()。 docs.doctrine-project.org/projects/doctrine-orm/en/latest/…
-
谢谢,我还有一个问题......如果我想获得我定义的真实列,比如 product_id 而不是 productId 我该怎么做?
-
我认为您还没有完全掌握对象关系管理器的概念。听起来你想在 sql 级别工作,这很好。看看 Doctrine 的数据库访问层:docs.doctrine-project.org/projects/doctrine-dbal/en/latest
标签: doctrine-orm doctrine symfony