[英]Doctrine2 Many to Many Multiple Join on Table
My schema looks like this: 我的架构如下所示:
items - item_id, ...
items_item_types - item_id, item_type_id
item_types - item_type_id, ...
I need a query that will get items with ALL the item types given. 我需要一个查询,该查询将获取具有给定所有项目类型的项目。 For example, let's say item 1 is type 10, and item 2 is types 10, 11, and 12. I'm given 10 and 11, item 1 wouldn't be returned but item 2 would. 例如,假设第1项是类型10,第2项是类型10、11和12。给定10和11,则不会返回第1项,但会返回第2项。
To clarify further: 为了进一步说明:
--------------------------
| item_id | item_type_id |
| 1 | 10 |
| 2 | 10 |
| 2 | 11 |
| 2 | 12 |
--------------------------
I can do this easily in SQL, for example 例如,我可以在SQL中轻松完成此操作
select * from items
join item_item_types join_table1 on items.item_id = join_table1.item_id and join_table1.item_type_id = 10
join item_item_types join_table2 on items.item_id = join_table1.item_id and join_table2.item_type_id = 11
Which would return item 2 in this case 在这种情况下将返回项目2
The query is already quite complicated and I'm being passed a reference to the QueryBuilder object, so I cannot use native SQL (as far as I know). 该查询已经非常复杂,并且正在向我传递对QueryBuilder对象的引用,因此,就我所知,我无法使用本机SQL。 What my code looks like: 我的代码如下所示:
function addItemTypesToQuery(&$qb, $itemTypes) {
foreach($itemTypes as $key => $value) {
$qb->join('item.itemTypes', 'item_type' . $key, 'WITH', ???)
}
}
I'm not sure what the join condition needs to be to mirror the SQL. 我不确定镜像SQL的联接条件是什么。 Doctrine skips over the intermediary step of joining the item_item_types table but I need to set join conditions on THAT, not on the item_types table. Doctrine跳过了加入item_item_types表的中间步骤,但是我需要在THAT而不是item_types表上设置连接条件。
Doctrine will handle the joins automatically and search a set of values in the Many-to-Many table using either the ItemType
entity ID or entity reference. Doctrine将自动处理联接,并使用ItemType
实体ID或实体引用在“多对多”表中搜索一组值。 This is done with the MEMBER OF
DQL: 这是通过DQL MEMBER OF
完成的:
function addItemTypesToQuery(&$qb, $itemTypes) {
$i = 0;
foreach($itemTypes as $key => $value) {
$qb->addWhere('?'.$i.' MEMBER OF item.itemTypes')
->setParameter($i++, $key)
;
}
}
Note: I don't know the parent structure of your QueryBuilder, but you could run into problems if you've already set parameters with the numeric identifiers. 注意:我不知道QueryBuilder的父结构,但是如果您已经用数字标识符设置了参数,则可能会遇到问题。 One alternative is: 一种选择是:
function addItemTypesToQuery(&$qb, $itemTypes) {
$i = 0;
foreach($itemTypes as $key => $value) {
$qb->addWhere(':itemWhere'.$i.' MEMBER OF item.itemTypes')
->setParameter('itemWhere'.$i++, $key)
;
}
}
Note that $key
must be the primary identifier of the ItemType
entity. 请注意, $key
必须是ItemType
实体的主要标识符。 You can also use $value
if it's the actual ItemType
entity reference. 如果它是实际的ItemType
实体引用,则也可以使用$value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.