我有一个理论模型(Assignment),它与另一个模型(Region)有着多对一的关系。赋值由用户拥有(每个用户一次只有一个分配),我试图使用indexBy让用户的分配数组由分配区域的ID键决定。然而,我只得到标准的0.n数字键。
当我尝试运行像SELECT am, reg, user FROM Assignment am INDEX BY [...] JOIN am.region reg JOIN am.user user WHERE user.id = ?1这样的DQL查询时,这些值中没有一个是按工作方式索引的:
region (错误:无效的PathExpression。必须是StateFieldPathExpression。)region_id (错误:类...\Assignment没有名为region_id的字段或关联)region.id (错误:字符串的预期结束,got '.')这个是可能的吗?如果不是,那么在没有User的区域访问indexBy分配的方便方法是什么?
发布于 2014-04-23 12:09:16
我今天也在处理同样的问题。幸运的是,我找到了解决方案:)
首先,您必须在ORM映射中声明其他列:
Abdulklarapl\My\EntityA:
type: entity
table: entityA
manyToOne:
entityB:
targetEntity: EntityB
joinColumn:
name: label_id
referencedColumnName: id
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
value:
type: text
entityB_id:
type: integer
lifecycleCallbacks: { }注意,我已经将entityB_id声明为字段+,我通过添加joinColumn子句配置了manyToOne关系
因此,现在可以使用entityB_id作为标量值。
$doctrine->getEntityManager()->createQueryBuilder()
->select('c')
->from('AbdulklaraplMyBundle:EntityA', 'c', 'c.entityB_id')
->getQuery()->getResult();它将返回assoc数组。
[
c.entityB_id: {
id: "",
value: ""
entityB_id: ""
}
]您还可以使用AbstractQuery::HYDRATE_ARRAY作为getResult()的参数-它将返回带数组的assoc数组,而不是对象。
发布于 2016-09-08 08:27:30
如果您需要使用外键进行索引,例如"region_id“,则在您的映射中可以:
/**
* @ORM\OneToMany(targetEntity="Region", mappedBy="user", indexBy="region_id")
*/
protected $regions;特征是加在这里。
不幸的是,似乎没有文档表明您必须使用外键本身的列的名称。
使用索引关联
发布于 2012-09-06 04:49:55
导入查询类(可选):
use \Doctrine\ORM\Query;创建查询:
$query = $this->data->em->createQuery('
SELECT a
FROM Assignment a
INDEX BY a.reg //to set array custom key
WHERE a.user = :user');
$query->setParameter('user', 3); //user with id 3
//set the hidration mode in order to work with read-only arrays
$assignments = $query->getResult(Query::HYDRATE_ARRAY); https://stackoverflow.com/questions/12268955
复制相似问题