1

我有一个名为“tile”的实体,与另一个名为“coins”的实体具有多对多关系。

/**
 * @ORM\ManyToMany(targetEntity="Coin")
 * @ORM\JoinTable(name="coin",
 *      joinColumns={@ORM\JoinColumn(name="tile_id", referencedColumnName="tile_id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="coin_id", referencedColumnName="coin_id")}
 *      )
 **/
protected $coins;

我有一个页面列出了瓷砖及其所有相关硬币。一个页面上可能有很多硬币和瓷砖,使用延迟加载可以在单个页面上放置 100-300 个数据库查询。我试图通过使用 leftJoin 来避免这种情况。

public function getUserTiles($id)
{                    
        $qb = $this->createQueryBuilder('b')
       ->select('b', 'z')
       ->leftJoin('b.coins', 'z')
       ->leftJoin('z.userInfo', 'u')
       ->add('where', "b.userId = ".$id." AND b.status = 'COMPLETED'")
       ->add('orderBy', "b.checkinDate DESC");

    return $qb->getQuery()
              ->getResult();      
}

这给了我以下错误:

*[2/2] DBALException: An exception occurred while executing '

SELECT t0_.tile_id AS tile_id0, t0_.quilt_id AS quilt_id1, t0_.user_id AS user_id2, t0_.comment AS comment3, t0_.checkout_date AS checkout_date4, t0_.checkin_date AS checkin_date5, t0_.x AS x6, t0_.y AS y7, t0_.status AS status8, t0_.completed_neighbors AS completed_neighbors9, t0_.required_completed_neighbors AS required_completed_neighbors10, t0_.visible AS visible11, t0_.visible_date AS visible_date12, t0_.count_towards_coins AS count_towards_coins13, c1_.coin_id AS coin_id14, c1_.user_id AS user_id15, c1_.tile_id AS tile_id16, c1_.comment AS comment17, c1_.date_given AS date_given18, c1_.status AS status19, c1_.origin AS origin20, t0_.quilt_id AS quilt_id21, t0_.user_id AS user_id22, c1_.tile_id AS tile_id23, c1_.user_id AS user_id24
FROM tile t0_ **LEFT JOIN coin *c1_* ON t0_.tile_id = c1_.tile_id
LEFT JOIN coin *c1_* ON c1_.coin_id = c1_.coin_id**
LEFT JOIN user_info u2_ ON c1_.user_id = u2_.user_id
WHERE t0_.user_id = 14 AND t0_.status = 'COMPLETED'
ORDER BY t0_.checkin_date DESC':

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'c1_'* 

如您所见,它尝试使用相同的别名加入硬币表两次。我究竟做错了什么?

4

2 回答 2

0

Try:

$this->createQueryBuilder('b')
    ->select('b')
    ->addSelect('z')
    ->leftJoin('b.coins', 'z')
    ->leftJoin('z.userInfo', 'u')
    ->where("b.userId = :id AND b.status = 'COMPLETED'")
    ->orderBy('b.checkinDate', 'DESC')
    ->setParameter('id', $id)
    ->getQuery('b.checkinDate DESC')
    ->getSingleResult();
于 2013-05-18T22:03:36.540 回答
0

我通过将 ManyToMany 关系更改为 OneToMany 解决了这个问题,因为它本来应该是。

于 2013-05-19T15:15:50.457 回答