1

I do have a simple one-to-one association (Shop has a Place) and want to make a simple query over the Shop.

Do I automatically get also the name of the place? Automatically means that I don't need to enter any where or join.

<?php
/** @Entity **/
class Shop
{
    // ...

    /**
     * @OneToOne(targetEntity="Place")
     * @JoinColumn(name="place_id", referencedColumnName="id")
     **/
    private $place;

    // ...
}

/** @Entity **/
class Place
{
    private $id;
    private $name;
}

Select would look like this:

'SELECT s
FROM Shop s'
Bartosz Stankiewicz
  • 323
  • 1
  • 2
  • 10

2 Answers2

2

Yes you can in most cases. Doctrine has different fetch modes. This would be the - default - lazy mode and it will make many small requests so it is more suited for rapid prototyping. Most of the time you'll need either to use a JOIN clause in your query or you might be able to sipmply set the fetch mode to EAGER it supports joins now according to last comment on the answer here: doctrine2 loads one-to-many associations with fetch mode eager using too many SQL queries

You can also use the profiler to see the actual queries.

For fetch modes refer to http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql

For joins refer to: https://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#joins

Community
  • 1
  • 1
Tom Tom
  • 3,680
  • 5
  • 35
  • 40
1

No, you would need to do a join in order to get the name of the place; the most you could do without a join would be to get the place's ID.

So your query should be:

SELECT s, p
FROM Shop s
JOIN s.place

(Assuming you want to do an inner join; a LEFT JOIN is also possible.)

Of course, if you don't do a join, Doctrine will get the place's name for you automatically when you ask for it using lazy-loading, but that involves another query to the database behind the scenes.

Matt Browne
  • 12,169
  • 4
  • 59
  • 75
  • Side-note: this is relevant to one-to-one joins in general, though not to your particular question. Sometimes Doctrine will lazy-load the related object even if you don't ask it to (if you don't do a join in the query). See http://stackoverflow.com/questions/9848747/primary-key-of-owning-side-as-a-join-column – Matt Browne Aug 03 '14 at 21:27