Symfony+Doctrine查询嵌套关联字段报PathExpression错误及结果格式化问题
问题1报错原因
Invalid PathExpression. Must be a StateFieldPathExpression错误的根本原因是Doctrine DQL不支持在select中直接访问多层嵌套的关联属性,必须先显式join对应的关联实体,才能引用关联实体的字段。
问题2返回格式实现
要获取你需要的纯字符串数组结构,使用getSingleColumnResult直接获取单字段查询结果,再组装成对应结构即可。
修复后的Repository方法
public function getDistinctBrandsAndTypes() { // 查询去重的品牌名称 $brandQuery = $this->createQueryBuilder('product') ->select('b.name') ->distinct(true) ->join('product.idProductModel', 'pm') // 先关联ProductModel实体 ->join('pm.idBrand', 'b') // 再关联Brand实体 ->getQuery(); $brands = $brandQuery->getSingleColumnResult(); // 查询去重的类型名称 $typeQuery = $this->createQueryBuilder('product') ->select('t.name') ->distinct(true) ->join('product.idProductModel', 'pm') ->join('pm.idType', 't') // 关联Type实体 ->getQuery(); $types = $typeQuery->getSingleColumnResult(); // 组装成目标结构 return [ 'brands' => $brands, 'types' => $types ]; }
只要你的实体关联配置正确(Product的
idProductModel是ManyToOne关联到ProductModel实体、ProductModel的idBrand/idType是正确的关联映射),该方法返回的数组序列化后就是你需要的JSON格式。
你也可以改成单次查询同时获取两个字段再拆分结果,分开查询的写法更易读、更方便新手调试。
内容的提问来源于stack exchange,提问作者Naima
相关产品推荐
相关产品推荐

