douhe1002 2017-08-16 11:24
浏览 78
已采纳

Doctrine和ManyToOne实体

I have two entities, country and Province, and I have set up a many-to-one relation in the Province entity:

Entity/Province

/**
 * @var \AppBundle\Entity\Country
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Country")
 * @ORM\JoinColumn(name="ubicacionpaisid", referencedColumnName="id")
 *
 */
private $ubicacionpaisid;

Here I get all results using the Province entity:

 $cb = $this->getDoctrine()
        ->getEntityManager()
        ->getRepository(Province::class)
        ->createQueryBuilder('a');

However, if I run:

 var_dump($cb->getQuery()->getDQL());

it returns:

string(41) "SELECT a FROM AppBundle\Entity\Province a"

What I expected to see was a query that joins the Country entity, into the Province entity in the SQL.

What am I missing ?

  • 写回答

3条回答 默认 最新

  • dongyang1518 2017-08-16 13:37
    关注

    I realize 2 people gave answers that just say to use EAGER loading of the association. But I can't recommend that. This makes so many assumptions about your project and how you'd always want to join that association no matter what, and can even cause issues with forms and creating unexpected behavior.

    Plus, the user already is showing that they're using a custom QueryBuilder call to grab the data, so why not explicitly use the join?

    For example:

    $cb = $this->getDoctrine()->getEntityManager()->getRepository(Province::class)
        ->createQueryBuilder('p')
        ->select('p, c')
        ->join('p.ubicacionpaisid', 'c')
        ->getQuery()
        ->getResult()
    ;
    

    or better yet, from with a ProvinceRepository:

    return $this->createQueryBuilder('p')
        ->select('p, c')
        ->join('p.ubicacionpaisid', 'c')
        ->getQuery()
        ->getResult()
    ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?