dpp78272 2015-04-21 17:58
浏览 70
已采纳

Doctrine2多对多加入表

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.

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

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

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). 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. 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.

  • 写回答

1条回答 默认 最新

  • duanbi3385 2015-04-21 18:53
    关注

    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. This is done with the MEMBER OF DQL:

    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. 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. You can also use $value if it's the actual ItemType entity reference.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置