Darmen
Darmen

Reputation: 4881

Doctrine: join one-to-one relation

Suppose we have two models: Post and ViewsCount. Relation type is 1:1.

Now I want to retrieve last 5 posts with their views stats:

$posts = PostTable::getInstance()->createQuery('p')
    ->leftJoin('p.ViewsCount') // relation name is "ViewsCount"
    ->orderBy('p.created_at DESC')
    ->limit(5)
    ->execute();

But, there is no luck. It throws an error. If I remove joining - everything is ok.

So, my question is - How to automatically join/retrieve one-to-one relation in Doctrine to avoid lot's of additional queries?

Upvotes: 1

Views: 2174

Answers (2)

cuhuak
cuhuak

Reputation: 498

Is seems that you should define relations properly. For each model define relations with type key (type:one).

Upvotes: 0

Jakub Zalas
Jakub Zalas

Reputation: 36241

You have an error in syntax. You also need to tell doctrine you want to retrieve the ViewCount fields:

$posts = PostTable::getInstance()->createQuery('p')
  ->select('p.*, vc.*')
  ->leftJoin('p.ViewsCount vc')
  ->orderBy('p.created_at DESC')
  ->limit(5)
  ->execute();

Upvotes: 1

Related Questions