Doctrine 2 - ORM
  1. Doctrine 2 - ORM
  2. DDC-357

Lazy-loading in OneToOne-bidirectional associations not working for inverse side

    Details

    • Type: Bug Bug
    • Status: Resolved
    • Priority: Minor Minor
    • Resolution: Won't Fix
    • Affects Version/s: 2.0-ALPHA4
    • Fix Version/s: None
    • Component/s: ORM
    • Security Level: All
    • Labels:
      None
    • Environment:
      XAMPP 1.7.3

      Description

      I am referring to the following situation:
      http://www.doctrine-project.org/documentation/manual/2_0/en/association-mapping#one-to-one,-bidirectional

      In this example: if I fetch an object of type "Customer" from my database, a second query is executed immediately that fetches the corresponding "Cart" even if I do not access the $cart property of "Customer". Annotating fetch="LAZY" to the $cart property does not make any difference. This is even worse in case of self-referencing objects, e.g. those having at most one parent object and at most one child object. Here, all associations are created by single database queries at once (e.g. fetching the child object, then the child of the child object and so forth).

      By contrast, OneToMany associations are lazy-loaded from the inverse side (as expected).

      Perhaps I should add, that I am using annotation mappings for my entities (no YAML, no XML).

        Issue Links

          Activity

          Marcel Walter created issue -
          Hide
          Roman S. Borschel added a comment -

          This is expected behavior. Inverse sides of one-to-one associations can not be lazy, technically. There is no foreign key on the inverse side, hence it is impossible to decide whether to proxy it or not. We must query for the associated object or join it. Note that this only affects inverse sides of single-valued associations, that is, really only the inverse side of bidirectional one-to-one associations.

          In the future, you can use fetch="EAGER" to automatically load the associated objects in a join whenever the inverse side object is loaded. That is a planned enhancement.
          So when fetch="EAGER" is used on a single-valued association, it is automatically fetch-joined, even when you just do ->find('Object', 1).

          Right now, you can use an eager fetch join in DQL to avoid the extra query. Fetch-joins on single-valued associated are usually very cheap, compared to collections.

          Note that you need a join anyway, because the foreign key is on the other side, thus it doesnt make much sense to join just for the sake of getting the foreign key. If we join we can as well grab the associated object completely.

          The "fetch" mode is a "hint", that means, Doctrine tries to do that when possible. Its not always possible.

          If you have a suggestion, feel free to speak up.

          Show
          Roman S. Borschel added a comment - This is expected behavior. Inverse sides of one-to-one associations can not be lazy, technically. There is no foreign key on the inverse side, hence it is impossible to decide whether to proxy it or not. We must query for the associated object or join it. Note that this only affects inverse sides of single-valued associations, that is, really only the inverse side of bidirectional one-to-one associations. In the future, you can use fetch="EAGER" to automatically load the associated objects in a join whenever the inverse side object is loaded. That is a planned enhancement. So when fetch="EAGER" is used on a single-valued association, it is automatically fetch-joined, even when you just do ->find('Object', 1). Right now, you can use an eager fetch join in DQL to avoid the extra query. Fetch-joins on single-valued associated are usually very cheap, compared to collections. Note that you need a join anyway, because the foreign key is on the other side, thus it doesnt make much sense to join just for the sake of getting the foreign key. If we join we can as well grab the associated object completely. The "fetch" mode is a "hint", that means, Doctrine tries to do that when possible. Its not always possible. If you have a suggestion, feel free to speak up.
          Roman S. Borschel made changes -
          Field Original Value New Value
          Status Open [ 1 ] Resolved [ 5 ]
          Resolution Won't Fix [ 2 ]
          Hide
          Roman S. Borschel added a comment -

          If you have an example of a self-referential association that causes extreme ripple-loading of the whole hierarchy, can you please file a new jira issue for that?

          Thanks!

          Show
          Roman S. Borschel added a comment - If you have an example of a self-referential association that causes extreme ripple-loading of the whole hierarchy, can you please file a new jira issue for that? Thanks!
          Hide
          Roman S. Borschel added a comment -

          Here some other ways to get around the extra queries:

          1) $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);

          2) $query->getArrayResult() / ->getScalarResult()

          Just for the sake of completeness.

          Show
          Roman S. Borschel added a comment - Here some other ways to get around the extra queries: 1) $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); 2) $query->getArrayResult() / ->getScalarResult() Just for the sake of completeness.
          Hide
          Konstantin added a comment -

          Why we cannot create proxy without FK?

          Show
          Konstantin added a comment - Why we cannot create proxy without FK?
          Benjamin Eberlei made changes -
          Workflow jira [ 10926 ] jira-feedback [ 14286 ]
          Benjamin Eberlei made changes -
          Workflow jira-feedback [ 14286 ] jira-feedback2 [ 16150 ]
          Benjamin Eberlei made changes -
          Workflow jira-feedback2 [ 16150 ] jira-feedback3 [ 18403 ]
          Hide
          Christian S. added a comment -

          Hi. I have a problem with this solution.

          I have an entity "Document" with an one-to-one association to an entity called "File". In the database table of the File entity I store the content of a file. So if I load for example 20 Documents I do not want the associated Files to be loaded, because this leads to memory problems.

          I do not understand the explanation

          There is no foreign key on the inverse side, hence it is impossible to decide whether to proxy it or not.


          In a one-to-many association there is no foreign key on the inverse side, too. Why not always load a proxy like in a one-to-many association?

          Plus: There is no documentation about this, neither on http://docs.doctrine-project.org/en/latest/reference/association-mapping.html nor http://docs.doctrine-project.org/en/latest/reference/unitofwork-associations.html

          Show
          Christian S. added a comment - Hi. I have a problem with this solution. I have an entity "Document" with an one-to-one association to an entity called "File". In the database table of the File entity I store the content of a file. So if I load for example 20 Documents I do not want the associated Files to be loaded, because this leads to memory problems. I do not understand the explanation There is no foreign key on the inverse side, hence it is impossible to decide whether to proxy it or not. In a one-to-many association there is no foreign key on the inverse side, too. Why not always load a proxy like in a one-to-many association? Plus: There is no documentation about this, neither on http://docs.doctrine-project.org/en/latest/reference/association-mapping.html nor http://docs.doctrine-project.org/en/latest/reference/unitofwork-associations.html
          Hide
          Roman S. Borschel added a comment -

          It is pretty simple, in a one-to-many association where the one-side is the inverse side, it holds a collection. The collection may be empty or not but there can always be a collection so it easy and correct to always put a proxy collection there.

          If you have a single-valued side that is the inverse side, how can you decide whether to put a proxy object there or not? Without seeing the foreign key you have no way to distinguish between: There is no associated object (and thus putting a proxy object in place would by simply wrong) or there is one and of which type it is, if inheritance is involved (since putting a proxy of the wrong type in is also wrong).

          This is as far as I recall, maybe Benjamin knows more on the current state.

          Show
          Roman S. Borschel added a comment - It is pretty simple, in a one-to-many association where the one-side is the inverse side, it holds a collection. The collection may be empty or not but there can always be a collection so it easy and correct to always put a proxy collection there. If you have a single-valued side that is the inverse side, how can you decide whether to put a proxy object there or not? Without seeing the foreign key you have no way to distinguish between: There is no associated object (and thus putting a proxy object in place would by simply wrong) or there is one and of which type it is, if inheritance is involved (since putting a proxy of the wrong type in is also wrong). This is as far as I recall, maybe Benjamin knows more on the current state.
          Roman S. Borschel made changes -
          Assignee Roman S. Borschel [ romanb ] Benjamin Eberlei [ beberlei ]
          Hide
          Christian S. added a comment -

          Okay, I see the problem. But it would be nice if this behaviour could be documented.

          Isn't it possible to always put a special proxy object there and if it get's accessed via lazy loading and Doctrine detect's that there is no associated entity, then the proxy will be replaced by a NULL value?

          Show
          Christian S. added a comment - Okay, I see the problem. But it would be nice if this behaviour could be documented. Isn't it possible to always put a special proxy object there and if it get's accessed via lazy loading and Doctrine detect's that there is no associated entity, then the proxy will be replaced by a NULL value?
          Hide
          Hernan Rajchert added a comment - - edited

          Hi, I've been faced with this issue some times. I tent to solve this by doing two unidirectional one-to-one. Then I deal with the non existing relationship using a method called getRelation that I defined in a BaseModel.
          I have created this method because Doctrine filled up with a Proxy when I fetch the entity without its relationship (then accesing the object would throw an Exception), and filled up with null when the object was eagerly fetched (left join) but no relationship was found.
          I think we could add this getRelation in the entitymanager or a trait after php 5.4.

          Show
          Hernan Rajchert added a comment - - edited Hi, I've been faced with this issue some times. I tent to solve this by doing two unidirectional one-to-one. Then I deal with the non existing relationship using a method called getRelation that I defined in a BaseModel. I have created this method because Doctrine filled up with a Proxy when I fetch the entity without its relationship (then accesing the object would throw an Exception), and filled up with null when the object was eagerly fetched (left join) but no relationship was found. I think we could add this getRelation in the entitymanager or a trait after php 5.4.
          Hernan Rajchert made changes -
          Attachment getRelation.php [ 11415 ]
          Hernan Rajchert made changes -
          Comment [ Hi, I've been faced with this issue some times. I tent to solve this by doing two unidirectional one-to-one. Then I deal with the non existing relationship using a method called getRelation that I defined in a BaseModel.

          I have created this method because Doctrine filled up with a Proxy when I fetch the entity without its relationship (then accesing the object would throw an Exception), and filled up with null when the object was eagerly fetched (left join) but no relationship was found.

          I think we could add this getRelation in the entitymanager or a trait after php 5.4.
          ]
          Hide
          Martin Štekl added a comment -

          Hi,
          I think that idea of special proxy object is not so bad. However if you do not want to create special proxy object and build some logic around it then why do you not want to satisfy at least one of two (currently unsupported) cases?
          I mean the case in which the object type is used in inheritance. This case is easier to solve in my opinion (similar to @OneToMany) and usually wanted. It is better to support at least one possibility then none.

          Show
          Martin Štekl added a comment - Hi, I think that idea of special proxy object is not so bad. However if you do not want to create special proxy object and build some logic around it then why do you not want to satisfy at least one of two (currently unsupported) cases? I mean the case in which the object type is used in inheritance. This case is easier to solve in my opinion (similar to @OneToMany) and usually wanted. It is better to support at least one possibility then none.
          Hide
          Filip Procházka added a comment -

          I'm proposing a solution to this "Won't Fix" that I disagree with https://github.com/doctrine/doctrine2/pull/970

          Show
          Filip Procházka added a comment - I'm proposing a solution to this "Won't Fix" that I disagree with https://github.com/doctrine/doctrine2/pull/970
          Marco Pivetta made changes -
          Link This issue is referenced by DDC-3011 [ DDC-3011 ]
          Hide
          Doctrine Bot added a comment -

          A related Github Pull-Request [GH-970] was closed:
          https://github.com/doctrine/doctrine2/pull/970

          Show
          Doctrine Bot added a comment - A related Github Pull-Request [GH-970] was closed: https://github.com/doctrine/doctrine2/pull/970
          Hide
          Misha Bosiy added a comment -

          My solution:
          Two entities with one-to-one reference Site and Url:

          *********************************

          Site

          /**

          • @var Url
            *
          • @ORM\OneToOne(targetEntity="Url", cascade= {"persist"}

            )

          • @ORM\JoinColumns( { * @ORM\JoinColumn(name="url_id", referencedColumnName="url_id") * }

            )
            */
            private $url;

          /**

          • @return Url
            */
            public function getUrl() { return $this->url; }

          *********************************

          Url

          /**

          • @var \Doctrine\ORM\PersistentCollection
            *
          • @ORM\OneToMany(targetEntity="Site", mappedBy="url")
            */
            private $site;

          /**

          • @return Site|null
            */
            public function getSite() { return ($this->site->first() !== false) ? $this->site->first() : null; }

          *********************************

          Queries:

          $url = $urlRepo->createQueryBuilder('u')
          >where('u.url_id = :url_id')>setParameter('url_id', 19518)
          ->getQuery()
          ->getOneOrNullResult();

          We have only 1 query to DB.

          When call:
          $url->getSite();

          One more query appears. So lazy load work perfect!

          ********************************

          If with join:
          $url = $urlRepo->createQueryBuilder('u')
          ->select('u', 's')
          ->join('u.site', 's')
          >where('u.url_id = :url_id')>setParameter('url_id', 19518)
          ->getQuery()
          ->getOneOrNullResult();

          When call:
          $url->getSite();

          Only 1 query to DB.

          Show
          Misha Bosiy added a comment - My solution: Two entities with one-to-one reference Site and Url: ********************************* Site /** @var Url * @ORM\OneToOne(targetEntity="Url", cascade= {"persist"} ) @ORM\JoinColumns( { * @ORM\JoinColumn(name="url_id", referencedColumnName="url_id") * } ) */ private $url; /** @return Url */ public function getUrl() { return $this->url; } ********************************* Url /** @var \Doctrine\ORM\PersistentCollection * @ORM\OneToMany(targetEntity="Site", mappedBy="url") */ private $site; /** @return Site|null */ public function getSite() { return ($this->site->first() !== false) ? $this->site->first() : null; } ********************************* Queries: $url = $urlRepo->createQueryBuilder('u') >where('u.url_id = :url_id') >setParameter('url_id', 19518) ->getQuery() ->getOneOrNullResult(); We have only 1 query to DB. When call: $url->getSite(); One more query appears. So lazy load work perfect! ******************************** If with join: $url = $urlRepo->createQueryBuilder('u') ->select('u', 's') ->join('u.site', 's') >where('u.url_id = :url_id') >setParameter('url_id', 19518) ->getQuery() ->getOneOrNullResult(); When call: $url->getSite(); Only 1 query to DB.
          Hide
          Filip Procházka added a comment -

          That is not a solution but a workaround which we are also using.

          Show
          Filip Procházka added a comment - That is not a solution but a workaround which we are also using.
          Hide
          Misha Bosiy added a comment -

          I wrote it for people who has such problem and don't know what to do with not necessary subqueries.

          Show
          Misha Bosiy added a comment - I wrote it for people who has such problem and don't know what to do with not necessary subqueries.

          This list may be incomplete, as errors occurred whilst retrieving source from linked applications:

          • Request to http://www.doctrine-project.org/fisheye/ failed: Error in remote call to 'FishEye 0 (http://www.doctrine-project.org/fisheye/)' (http://www.doctrine-project.org/fisheye) [AbstractRestCommand{path='/rest-service-fe/search-v1/crossRepositoryQuery', params={query=DDC-357, expand=changesets[0:20].revisions[0:29],reviews}, methodType=GET}] : Received status code 503 (Service Temporarily Unavailable)

            People

            • Assignee:
              Benjamin Eberlei
              Reporter:
              Marcel Walter
            • Votes:
              0 Vote for this issue
              Watchers:
              9 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: