Doctrine 2 DQL - Select rows where a many-to-many field is empty?

后端 未结 4 725
北恋
北恋 2020-12-15 05:23

I have two classes in this example - DeliveryMethod and Country. They have a many-to-many relationship with each other.

What I want to do is select all DeliveryMetho

相关标签:
4条回答
  • 2020-12-15 05:27

    Use Doctrine's is empty

    It's specifically designed to check for empty associations:

    $qb->select('m')->from('DeliveryMethods', 'm')->where('m.countries is empty')
    

    See: Doctrine 2 ORM Documentation: Doctrine Query Language (search for "is empty")

    0 讨论(0)
  • 2020-12-15 05:40

    There is no need in joins and havings. Simply use SIZE function:

    $qb->select('m')
       ->from('DeliveryMethods','m')
       ->where('SIZE(m.countries) = 0');
    

    This will give you all methods without attached countries

    0 讨论(0)
  • 2020-12-15 05:47

    Can't join NULL values, IIRC. Apologies for the typo on twitter, should have said "can't".

    0 讨论(0)
  • 2020-12-15 05:51

    What about this? Assuming $qb is your query builder instance

    $qb->select('m')
       ->from('DeliveryMethods','m')
       ->leftJoin('m.countries','c')
       ->having('COUNT(c.id) = 0')
       ->groupBy('m.id');
    

    This would give you the DeliveryMethods which is associated with countries and count of the associated countries is 0

    0 讨论(0)
提交回复
热议问题