MySQL和Doctrine QueryBuilder来自三个表

时间:2017-02-13 16:29:09

标签: php mysql doctrine symfony

我正在使用Symfony 3和doctrine 2.5。共有三张桌子:

 a. user table:
      id     name
       1     Alex
       2     Jim
       3     Bob

 b. companies table
      id     name
       1     company1
       2     company2

 c. company_users containing the relationship, both user_id and company_id.
      id     company_id   user_id
       1     1            1
       2     2            1
       3     2            2

鉴于公司ID 2,最终结果应该是这样,但对于我的生活,我不能为它编写一个有效的Doctrine QueryBuilder方法

1   company2 - Alex
2   company2 - Jim

我有三个正在运行的MySQL查询,它们为我带来了理想的结果。 但对于我的生活,我无法将其中任何一个转换为至少一个有效的Doctrine查询。

使用MySQL查询(可能实际上会帮助这里的一些用户):

SELECT companies.name, user.username
FROM companies
LEFT JOIN company_users ON company_users.company_id = companies.id
LEFT JOIN user ON company_users.user_id = user.id WHERE companies.id = 2;

SELECT u.username, c.name
FROM user u, company_users cu, companies c
WHERE cu.user_id = u.id and cu.company_id = c.id and c.id = 2

SELECT companies.name, user.username
FROM companies
LEFT JOIN company_users
    INNER JOIN user
    ON company_users.user_id=user.id
ON company_users.company_id=companies.id WHERE companies.id=2;

我对Doctrine的QueryBuilder的尝试:

        ->select('u.username', 'c.name')
        ->from('companies','c')
        ->leftJoin('c', 'company_users', 'cu', 'company_users.company_id = companies.id')
        ->leftJoin('u', 'user', 'u', 'company_users.user_id = user.id')
        ->where('c.id = :companyId')
        ->setParameter('companyId', $companyId)
        ->getQuery()
        ->getResult();

2 个答案:

答案 0 :(得分:0)

为什么不在连接条件中使用别名? 'company_users.company_id = companies.id' - > 'cu.company_id = c.id'

左连接语法与您使用的语法不同。

  

公共函数leftJoin($ join,$ alias,$ conditionType = null,   $ condition = null,$ indexBy = null);

固定构建器

->select('u.username', 'c.name')
    ->from('companies','c')
    ->leftJoin('company_users', 'c', 'WITH', 'cu.company_id = c.id')
    ->leftJoin('user', 'u', 'WITH', 'cu.user_id = u.id')
    ->where('c.id = :companyId')
    ->setParameter('companyId', $companyId)
    ->getQuery()
    ->getResult();

答案 1 :(得分:0)

适用于Symfony 3和doctrine 2.5的queryBuilder的答案。

$query = $this->_em->createQueryBuilder()
        ->select('u.username', 'c.name', 'c.id')
        ->from('AppBundle\Entity\User','u')
        ->leftJoin('AppBundle\Entity\CompanyUsers', 'cu', 'WITH', 'cu.user = u.id')
        ->leftJoin('AppBundle\Entity\Companies', 'c', 'WITH', 'cu.company = c.id')
        ->where('u.id = :userId')
        ->setParameter('userId', $userId)
        ->getQuery()
        ->getResult();

    $result = [];
    $result['userName'] = $query[0]['username'];
    $result['userId'] = $userId;
    $result['companies'] = [];

    foreach ($query as $q) {
        $result['companies'][] = array('companyName' => $q['name'], 'companyId' => $q['id']);

    }

    return $result;