2016-11-16 6 views
0

子エンティティuser_has_clientと親エンティティclientの間に多対1の関係があります。ここで結合クエリから親エンティティを取得する

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 |  | 
+-----------+------------------+------+-----+---------+-------+ 

私はuser_has_client子エンティティのuser_idを含むクエリから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. 

をしてから、この1試してみました:

$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. 
+1

は関係の双方向のですか?言い換えれば、クライアントは関係の逆の側を保持していますか? – Wilt

+0

私はそうではないと思ったが、実際はそうだった。 – Stephane

答えて

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)); 
0

私はクライアント上のユーザープロパティについて知りました。つまり、その関係は双方向です。

だから私は、その後、次のクエリを使用してデータにアクセスできます。

$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(); 
関連する問題