вторник, 29 сентября 2009 г.

Symfony: Doctrine order by calculated field

Положим нам нужно вывести 10 наиболее комментируемых постов.
Кусок схемы:
Post:
tableName: blog_post
actAs:
Timestampable: ~
Taggable: ~
columns:
id: { type: integer(4), primary: true, autoincrement: true }
title: { type: string(255) }
extract: { type: string(1024) }
content: { type: string(4096) }
is_published: { type: boolean, default: false }

Comment:
tableName: blog_comment
actAs:
Timestampable: ~
columns:
id: { type: integer(4), primary: true, autoincrement: true }
post_id: { type: integer(4), notnull: true }
name: { type: string(100) }
email: { type: string(100) }
content: { type: string(4096) }
subscribe: { type: boolean, default: false }
relations:
Post:
class: Post
local: post_id
foreign: id
foreignAlias: PostComments
type: one
foreignType: many
onDelete: CASCADE


Получим популярные посты одним запросом:
  public function executeGetMostCommentedBlogPosts()
{
$q = Doctrine_Query::create()
->select('p.*')
->addSelect('(SELECT count(*) FROM PostComments pc WHERE pc.post_id = p.id) as comments_count')
->from('Post p')
->where('p.is_published', true)
->orderBy('comments_count DESC')
->addOrderBy('d.created_at DESC')
->limit(10);

$this->posts = $q->execute();
}