从连接查询中获取父实体

时间:2016-11-16 17:07:22

标签: php zend-framework2 inner-join

我在user_has_client子实体和client父实体之间存在多对一关系。

这是user_has_client表:

MariaDB [extrapack]> desc user_has_client;
+-----------+------------------+------+-----+---------+-------+
| Field     | Type             | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| user_id   | int(10) unsigned | NO   | PRI | NULL    |       |
| client_id | int(10) unsigned | NO   | PRI | NULL    |       |
+-----------+------------------+------+-----+---------+-------+

我想从涉及client子实体的user_id的查询中返回user_has_client个父实体的列表。

我首先尝试过这个:

 $query = $this->getEntityManager()->createQueryBuilder()
 ->select('c')
 ->from('Application\Entity\UserHasClient', 'uc')
 ->innerJoin('uc.client', 'c')
 ->where('uc.user_id = :user_id')
 ->setMaxResults(10)
 ;
 $query->setParameters(array('user_id' => $user_id));

它给了我以下错误:

[Semantical Error] line 0, col -1 near 'SELECT c
   ': Error: Cannot select entity through identification variables without choosing at least one root entity alias.

然后尝试了这个:

$query = $this->getEntityManager()->createQuery(
    "SELECT c.client_id
    FROM Application\Entity\UserHasClient u
    INNER JOIN u.client c
    WHERE u.user_id = {$user_id}");

它给了我同样的错误:

Semantical Error] line 0, col -1 near 'SELECT c FROM': Error: Cannot select entity through identification variables without choosing at least one root entity alias.

2 个答案:

答案 0 :(得分:0)

我发现了客户端上的users属性,这意味着关系是双向的。

然后,我可以使用以下查询访问数据:

$query = $this->getEntityManager()->createQueryBuilder()
->select('c')
->from('Application\Entity\Client', 'c')
->innerJoin('c.users', 'u')
->andWhere("u.user_id = {$user_id}")
->orderBy('c.title', 'ASC')
->setMaxResults(10);
return $query->getQuery()->getArrayResult();

答案 1 :(得分:0)

如果关系是双向的,您可以使用如下查询:

$query = $this->getEntityManager()->createQueryBuilder()
    ->select('c')
    ->from('Application\Entity\Client', 'c')
    ->innerJoin('c.userHasClient', 'uc')
    ->where('uc.user_id = :user_id')
    ->setMaxResults(10);
$query->setParameters(array('user_id' => $user_id));