Cannot select entity through identification variables without choosing at least one root entity alias

北城以北 提交于 2020-01-02 04:10:31

问题


Ads entity is described by geographic information: Country> Region>County. The Ads entity is only linked with County. Consequently, retrieving Ads by countries will require us joining entities twice.

My goal is counting the number of Ads for a given country. For that, I tried this DQL query but without success:

public function getMotorsAdsCountByCountry($slug){
    $qb = $this->_em->createQueryBuilder()
            ->select("m.id, COUNT(m.id) AS cnt")
            ->from("MinnAdsBundle:MotorsAds", "m")
            ->join("m.county","county")->addSelect("county")
            ->join("county.region","region")->addSelect("region")
            ->join("region.country","country")->addSelect("country")
            ->where("country.slug=:slug")
            ->setParameter(":slug", $slug);
    return $qb->getQuery()->getSingleScalarResult();
}

The error I got is:

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

I have even seen a post regarding the same error in this link but without success.


回答1:


I found the solution:

    $qb = $this->_em->createQueryBuilder()
            ->select("COUNT(m.id) AS cnt")
            ->from("MinnAdsBundle:MotorsAds", "m")
            ->join("m.county","county")
            ->join("county.region","region")
            ->join("region.country","country")
            ->where("country.slug=:slug")
            ->setParameter(":slug", $slug);

I have just remove the addSelect() in addition to the modification of the select().




回答2:


try changing

->select("m.id, COUNT(m.id) AS cnt")

to

->select("m, COUNT(m.id) AS cnt")

or change hydration to array




回答3:


this is known as Doctrine limitation you should first join with MotorAds Entity like this

from('MinnAdsBundle','mi')->leftJoin(MotorsAds::class,'m','WITH','mi.motorsAds = m');

then you can select form MotorsAds directly refer to this answer



来源:https://stackoverflow.com/questions/28937655/cannot-select-entity-through-identification-variables-without-choosing-at-least

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!