0

I have an Article model and a Photo model, and I am currently using a query like this to join the two:

$q = Doctrine_Query::create()
       ->from('Article a')
       ->leftJoin('a.Photo p');

For binding them together, I have an ArticlePhoto model. In addition to article_id and photo_id fields, the model also has a priority INT field, with which I want to sort the Photos in the above query.

Any suggestions how I can achieve this, without having to join through a query like this:

$q = Doctrine_Query::create()
       ->from('Article a')
       ->leftJoin('a.ArticlePhoto ap')
       ->leftJoin('ap.Photo p')
       ->orderBy('ap.priority');

There is a lot of code expecting to find the first photo for the article in $article['Photo'][0], so I want to avoid having to change this. Thanks for any suggestions!

Nils
  • 780
  • 5
  • 16

2 Answers2

1

What's wrong with the joins? You can always rewrite your query to this:

$q = Doctrine_Query::create()
   ->from('Article a')
   ->leftJoin('a.ArticlePhoto ap, ap.Photo p')
   ->orderBy('ap.priority');

Which looks like a perfectly fine query without any magic. You need information from the ArticlePhoto table (for sorting), so doing an explicit join is the right thing to do.

Intru
  • 650
  • 1
  • 4
  • 16
0
$q = Doctrine_Query::create()
   ->from('Photo p')
   ->orderBy('priority');

The above will do the trick. Please know that there is not need to join tables which have relations(assuming that in your example the tables are having 1:m relation in the schema). You can acees the article object as stated bellow

$photoObjectCollection=$q->execute();
foreach($photoObjectCollection as $photoObject){
    $photoObject->Article->requiredField;
}
Jeevan
  • 309
  • 1
  • 6
  • `priority` is a field in `ArticlePhoto` not in `Photo`. I don't think your query do the trick. – j0k Apr 18 '12 at 11:55
  • And if I simply use $photoObject->Article->requiredField - it seems to use another DB query every time I access the Article field. I would rather request all needed data with the same query. – Nils Apr 18 '12 at 16:36