如何在Doctrine中搜索多对多的关系?

时间:2011-08-15 23:54:22

标签: php symfony1 doctrine

User:
  columns:
    id:
      type: integer(4)
      autoincrement: true
      primary: true
    username:
      type: string(255)

Group:
  tableName: group_table
  columns:
    id:
      type: integer(4)
      autoincrement: true
      primary: true
    name:
      type: string(255)
  relations:
    Users:
      foreignAlias: Groups
      class: User
      refClass: GroupUser

GroupUser:
  columns:
    group_id:
      type: integer(4)
      primary: true
    user_id:
      type: integer(4)
      primary: true
  relations:
    Group:
      foreignAlias: GroupUsers
    User:
      foreignAlias: GroupUsers


DB:
USER:
id | username
1  | john
2  | kate
3  | alan

GROUP:
id  | name
1   | admin
2   | mod
3   | kate (!)

USERGROUP:

id_user | id_group
1       | 1
2       | 1
1       | 2
3       | 3
3       | 2
2       | 3

我想制作搜索系统。我将搜索示例单词:“KATE”。 如何在KATE中搜索多对多的表?

在输入搜索中,我写“KATE”。我必须在Doctrine中使用WHERE LIKE。 这个查询必须如何看? 这应该向我显示用户名为Kate的所有用户以及组Kate的所有用户。

1 个答案:

答案 0 :(得分:1)

您的DQL会发生以下情况......

在组kate中搜索名为kate或Users的用户,返回用户和组

FROM User u LEFT JOIN u.Groups g WHERE u.username LIKE 'KATE' OR g.name LIKE 'KATE'

所以...

$qry = Doctrine_Query::create()
  ->from('User u')
  ->leftJoin("u.Groups g")
  ->where("u.username LIKE ? OR g.name LIKE ?", array('KATE','KATE'));