Relation to many and get without this

て烟熏妆下的殇ゞ 提交于 2019-12-13 22:24:58

问题


User:
id | name
1  | one
2  | two
3  | three
4  | four
5  | five


House:
id | name
1  | London
2  | Barcelona

UserHouse:
id_user | id_house
 1      |  1
 2      |  2
 4      |  1


$q = Doctrine_Query::create()
  ->from('User u')
   // many selectors here
  ->leftJoin('u.UserHouse uh')
  ->addWhere('????????');

$users = $q->execute();

I would like get all user without House (that is - not in table UserHouse) - this should return me user 3 and 5.

I know, i can use:

->from('UserHouse uh')

and next relation to User but i must have and use:

  ->from('User u')

because i use this query with many selectors - can't edit this. I must started with ->from('User u')

So what i must fill in ->addWhere('????????') that this return me users without house?

If not with Doctrine, how can i get this with simply SQL?


回答1:


In SQL, this type of query needs what is known as an EXCEPTION JOIN. Some RDBMSs actually implement this as a separate type (such as DB2), while others need to use a workaround. In your case, it amounts to (in SQL):

SELECT User.* 
FROM User
LEFT JOIN UserHouse
ON UserHouse.id_user = User.id
WHERE UserHouse.id_user IS NULL

Which will yield the expected 'not in a house' records.

There are similar examples in a number of places on this site.

I've never used Doctrine, so I can't help you there. But my best guess would be something like:

addWhere('uh IS NULL')

or

addWhere('uh.id_user IS NULL')


来源:https://stackoverflow.com/questions/12390904/relation-to-many-and-get-without-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!