2015-02-05 14 views
0

這裏是我的DB模式:如何在DQL條件下使用MAX函數?

| User |  | View  | 
*-------*  *----------* 
| id |  | id  | 
       | date  | 
| Movie |  | movie_id | 
*-------*  | user_id | 
| id | 
| title |  | Comment | 
| slug |  *-----------* 
| cover |  | id  | 
       | createdAt | 
       | view_id | 
       | user_id | 

我試圖做到的,是選擇具有至少一個視圖不是在電影發佈針對特定用戶的任何評論較早的電影,或者從未被評論由這個用戶。

我使用學說2,這裏就是我迄今所做的:

$this->createQueryBuilder('movie') 
    ->select('DISTINCT movie.id', 'movie.title', 'movie.slug', 'movie.cover') 
    ->addSelect('MAX(view.date) as lastViewedOn') 
    ->addSelect('MAX(comment.createdAt) as lastCommentedOn') 
    ->innerJoin('movie.views', 'view', 'WITH', 'view.user = :user') 
    ->leftJoin('movie.comments', 'comment', 'WITH', 'comment.author = :user') 
    ->andWhere(
     $qb->expr()->orX('lastCommentedOn IS NULL', 'lastViewedOn > lastCommentedOn') 
    ) 
    ->orderBy('lastViewedOn', 'DESC') 
    ->setParameter('user', $user) 
    ->getQuery() 
    ->getScalarResult() 
; 

問題是,這個請求會拋出異常:

QueryException: [Semantical Error] line 0, col 410 near 'lastCommentedOn': Error: 'lastCommentedOn' does not point to a Class. 

,我真的不明白爲什麼...

感謝您的啓示。

回答

0

我這個普通的SQL解決方案結束:

 SELECT m.id, m.title, m.slug, m.cover, v.maxDate 
      FROM movie m 
      INNER JOIN (
       SELECT movie_id, MAX(date) maxDate 
       FROM view 
       WHERE user_id = :user 
       GROUP BY movie_id 
      ) v ON m.id = v.movie_id 
      LEFT JOIN (
       SELECT id, movie_id, MAX(created_at) maxDate 
       FROM comment 
       WHERE author_id = :user 
       GROUP BY movie_id 
      ) c ON c.movie_id = m.id 
     WHERE m.online_on <= :from AND (m.offline_on IS NULL OR m.offline_on > :from) 
     AND (c.id IS NULL OR v.maxDate > c.maxDate) 
     ORDER BY v.maxDate DESC