在DQL中获取Doctrine关系

时间:2010-06-26 03:47:17

标签: php doctrine-query doctrine-1.2

我有三张桌子:

Project:
  ...
  relations:
    User:
      local: authorId
      foreign: id
    Users:
      class: User
      local: projectId
      foreign: userId
      refClass: UserProjects

User:
  ...
  relations:
    Projects:
      class: Project
      local: userId
      foreign: projectId
      refClass: UserProjects

UserProjects:
  columns:
      id:
        type: integer
        primary: true
        autoincrement: true
      userId: integer
      projectId: integer

我想要做的是写一个DQL语句来返回用户关联的项目。我想模仿以下内容:

SELECT p.* 
FROM user_projects AS up
LEFT JOIN project AS p ON up.projectid = p.id
LEFT JOIN user AS u ON up.userid = u.id
WHERE u.id = 1

通过学说指导,我想出了以下内容(你。*因为它抱怨你没有在select语句中使用):

$q = Doctrine_Query::create()
  ->from('Model_User u')
  ->select('u.*, p.*')
  ->leftJoin('u.Projects p');
$result = $q->execute();

它返回的是一个包含单个Model_User对象的数据集,其中“Projects”属性填入了相关项目。如果可能的话,我想让项目恢复,但我似乎无法弄明白。有可能吗?

1 个答案:

答案 0 :(得分:0)

我的关系错了。我必须执行以下操作,并且我能够让Doctrine自动构建正确的关系而无需使用DQL(所以我可以使用$ user-> UserProjects或$ project-> UserProjects)

Project:
  columns:
    id:
      type: integer
      primary: true
      autoincrement: true
    ...
    authorId: integer
    ...
  relations:
    User:
      local: authorId
      foreign: id
    Users:
      foreignAlias: Projects
      class: User
      refClass: UserProjects

User:
  columns:
    id:
      type: integer
      primary: true
      autoincrement: true
    ...

UserProjects:
  columns:
      id:
        type: integer
        primary: true
        autoincrement: true
      user_id: integer
      project_id: integer
  relations:
    Project:
      foreignAlias: UserProjects
    User:
      foreignAlias: UserProjects