兩個表我有一個實體,稱爲tracking
。它涉及User
和Course
。 我也有一個實體,稱爲credential
從而正式鏈接User
和Course
LEFT JOIN到在doctrine2查詢生成器
User <- Tracking -> Course
|| User <- Credential -> Course
跟蹤是某種形式的加盟實體,但它不是主要的兩個之間的連接。我有一個查詢,我已經有用戶和課程加入,並且如果它存在,我想要加入跟蹤。我試圖簡化我的例子。
$q->select(
'user.id',
'user.firstname',
'user.lastname',
'count(t) as courses',
'count(t.completed) as completed'
);
$q->from(Credential::class, 'c');
$q->from(Course::class, 'course');
$q->from(User::class, 'user');
$q->leftJoin(Tracking::class, 't', 'WITH', 't.user = user and t.course = course');
$q->where('c.user = user and c.object = course');
$q->groupBy('user');
我想在這裏實現的是一個列入註冊課程,課程數量和完成課程數量的用戶列表。
不幸的是,學說只能似乎加入到任何用戶表或過程表,而不是兩個。這甚至可能是一個mysql限制。我一遍又一遍地調試了這個問題 - 而且我用不同的例子多次遇到了這個問題 - 我似乎找不到一個解決方案,除了使用->from(Tracking)
這會消除那些還沒有開始任何課程的學生,並從他們還沒有開始的課程統計。我一遍又一遍地搜索,但很難搜索這個問題,而不是'如何與Doctrine連接兩個表'。
我得到我假設的錯誤Column not found: 1054 Unknown column 'c1_.id' in 'on clause'
意味着它可以加入對t.user = user
但不t.course = course
下面是實際的代碼和錯誤
$q = $this->em->createQueryBuilder();
$q->select(
'user.id',
'user.firstname',
'user.lastname',
'count(sc.id) as courses',
'count(ct.commenced) as commenced',
'count(ct.completed) as completed',
'avg(ct.scorePercent) as avgscore',
'avg(ct.totalTime) as avgtime'
);
$q->from(Security\Credential::class, 'c');
$q->from(Security\SecurableCourse::class, 'sc');
$q->from(Security\AccreditableInheritance::class, 'ai');
$q->from(Security\AccreditableUser::class, 'au');
$q->from(User::class, 'user');
$q->join(Tracking\CourseTracking::class, 'ct', 'WITH', 'ct.objectIdentity = sc and ct.user = user');
$q->where('sc = c.securable and ai.parent = c.accreditable and au = ai.child and user = au.user');
$q->andWhere('c.action = :action and sc.course in (:courses)');
$q->setParameter('action', 'study')->setParameter('courses', $courses);
$q->groupBy('user.id');
$users = $q->getQuery()->getScalarResult();
主義\ DBAL \異常\ InvalidFieldNameException(代碼:0 ):執行「SELECT u0_.id AS ID_0,u0_.firstname AS firstname_1發生異常,u0_.lastname AS lastname_2,計數(s1_.id)AS sclr_3,計數(t2_.commenced)AS sclr_4,計數(t2_.completed )AS sclr_5,avg(t2_.scorePercent)AS sclr_6,avg(t2_.totalTime)AS sclr_7 FROM Credential c3_ INNER JO IN跟蹤t2_ ON(t2_.objectIdentity_id = s1_.id AND t2_.user_id = u0_.id)AND t2_.dtype IN('coursetracking')AND((t2_.deleted IS NULL或t2_.deleted>'2016-04-26 8點33分31' 秒)),SecurableIdentity S1_,AccreditableInheritance a4_,AccreditableIdentity a5_,用戶u0_ WHERE(((s1_.id = c3_.securable_id AND a4_.parent_id = c3_.accreditable_id AND a5_.id = a4_.child_id AND u0_。 id = a5_.user_id)AND(c3_.action =? AND(s1_.course_id IN(?,?,?)))AND((u0_.deleted IS NULL or u0_.deleted>'2016-04-26 08:33:31')))AND(s1_.dtype IN ''和'a5_.dtype IN('accreditableuser'))GROUP BY u0_.id'與參數[\「study \」,\「46 \」,\「45 \」,\「160 \」]:\ n \ nSQLSTATE [42S22]:列未找到:1054未知列「s1_.id」在「關於條款」
這似乎是一種過於複雜的方式來做事情。你能否添加你的實體類的關係? – Richard
考慮閱讀一些顯示如何構建Doctrine 2查詢的文檔。提示:在查詢中永遠不會有更多$ qb-> form子句。 – Cerad