2013-10-14 18 views
0

我有2個表:上commentcommentuser如何在具有多個實體的Doctrine中執行以下查詢?

我有以下欄目:iduser_idconversation_idbody ...

user我有以下欄目:idusername ..

我想用doctrine執行以下查詢:

"SELECT c.*, u.username FROM comment c LEFT JOIN user u on c.user_id = u.id WHERE c.conversation_id = '5'" 

換句話說,當我收到評論列表時,我想要顯示user表中的name

我知道如何在SQL中完成它,但我無法在教條中做到這一點。

它應該是這個樣子:

$q = $this 
    ->createQueryBuilder('u') 
    ->where('u.conversationId = :conversationId') 
    ->setParameter('conversationId', $conversationId) 
    ->getQuery(); 

主義評論實體:

Test\SocialBundle\Entity\Comment: 
type: entity 
table: comment 
repositoryClass: Test\SocialBundle\Entity\CommentRepository 
fields: 
    id: 
     type: integer 
     id: true 
     generator: 
      strategy: AUTO 
    conversationId: 
     type: integer 
     nullable: false 
     column: conversation_id 
    userId: 
     type: integer 
     nullable: false 
     column: user_id 
    body: 
     type: string 
     nullable: false 
     length: '300' 
lifecycleCallbacks: { } 

學說用戶實體:

Test\UserBundle\Entity\User: 
type: entity 
table: user 
repositoryClass: Test\UserBundle\Entity\UserRepository 
fields: 
    id: 
     type: integer 
     id: true 
     generator: 
      strategy: AUTO 
    username: 
     type: string 
     length: '100' 
     nullable: true 
     column: username 
    name: 
     type: string 
     length: '100' 
     nullable: true 
     column: name 
manyToMany: 
    roles: 
     targetEntity: Role 
     joinTable: 
      name: user_role 
      joinColumns: 
       user_id: 
        referencedColumnName: id 
      inverseJoinColumns: 
       role_id: 
        referencedColumnName: id 
lifecycleCallbacks: { } 

謝謝!

+0

請張貼主義實體的結構。正如你可能知道的那樣,使用'ORM'移位邏輯來對象而不是外鍵。 –

回答

0

必須從CommentRepository調用請求,它必須看起來像

$qb = $this->createQueryBuilder('c'); 
$qb->select('c, u.username') 
    ->leftJoin('c.userId', 'u') 
    ->where($qb->expr()->eq('c.conversationId', $conversationId)); 
$qb->getQuery(); 
相關問題