Leandro Jacques
Leandro Jacques

Reputation: 453

Empty collection one-to-many in laravel using doctrine

I'm trying to use Doctrine with laravel and I was able to make all the mappings and return some results. But the problem is with one-to-many relation, that the many side ArrayCollection is empty.

I have two classes Project and Client, and a Client has many Project. In the project listing I do return client successfuly, but, at the Client side, the Project array is empty. Here is my summarized Client class:

<?php
namespace CodeProject\Entities\Doctrine;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="clients")
 */
class Client implements \JsonSerializable {

     /**
      * @ORM\Column(type="integer")
      * @ORM\Id
      * @ORM\GeneratedValue(strategy="AUTO")
      */
     private $id;

    /**
     *
     * @ORM\OneToMany(targetEntity="Project", mappedBy="client")
     */
    private $projects;

    public function __construct() {
        $this->projects = new ArrayCollection();
    }
}

Now the summarized Project class:

<?php

namespace CodeProject\Entities\Doctrine;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="projects")
 */
class Project implements \JsonSerializable {

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * 
     * @ORM\ManyToOne(targetEntity="Client", inversedBy="projects")
     * @ORM\JoinColumn(name="client_id", referencedColumnName="id")
     */
    private $client;
}

When I access the controller to bring information about client, here is what is being returned, note that projects is an empty array:

[
    {
        "id": 21,
        "name": "Dolores Osinski",
        "responsible": "Ashton Conn",
        "email": "[email protected]",
        "phone": "(936)177-7976",
        "address": "80311 Rossie Drives\nLake Brandyn, KS 39255-7560",
        "obs": "Aliquid harum architecto eum natus qui.",
        "created_at": "2017-03-19 16:33:39",
        "updated_at": "2017-03-19 16:33:39",
        "projects": {}
    }
]

On the Project side I get the client as you can see:

[
    {
        "id": 1,
        "name": "tenetur",
        "description": "Animi ut enim voluptas. Provident alias aut animi nemo repellendus. A dolores magni ducimus sit ex.",
        "progress": "39.00",
        "status": 4,
        "due_date": "1972-10-26 12:56:38",
        "created_at": "2017-03-19 16:33:45",
        "updated_at": "2017-03-19 16:33:45",
        "client": {
            "id": 21,
            "name": "Dolores Osinski",
            "responsible": "Ashton Conn",
            "email": "[email protected]",
            "phone": "(936)177-7976",
            "address": "80311 Rossie Drives\nLake Brandyn, KS 39255-7560",
            "obs": "Aliquid harum architecto eum natus qui.",
            "created_at": "2017-03-19 16:33:39",
            "updated_at": "2017-03-19 16:33:39",
            "projects": {}
        }
    }
]

What Am I missing?

UPDATE

My ClientRepository:

<?php

namespace CodeProject\Repositories;

use Doctrine\ORM\EntityRepository;

class ClientRepositoryDoctrine extends EntityRepository {

    public function getProjects($id) {
        $client = $this->find($id);
        return $client->getProjects();
    }

}

My ClientController at the function that lists projects for a certain client:

public function listProjects($id){
    return response()->json($this->repository->getProjects($id));
}

Even this way it's not listing anything.

Trying with DQL at my repository with fetch join:

<?php

namespace CodeProject\Repositories;

use Doctrine\ORM\EntityRepository;

class ClientRepositoryDoctrine extends EntityRepository {

    public function getProjects($id) {
        $result = $this->getEntityManager()->createQueryBuilder()->
            select('c, p')->
            from('CodeProject:Client', 'c')->
            join('c.projects', 'p')->
            where('c.id = :id')->
            setParameter(':id', $id)->getQuery()->getResult();
        return $result;
    }
}

And I got this, projects is still empty even with fetch join to force loading projects:

[
    {
        "id": 1,
        "name": "Mariam Jast",
        "responsible": "Imogene Schowalter",
        "email": "[email protected]",
        "phone": "05482413294",
        "address": "062 Block Parkway\nMireyabury, KS 63554-2056",
        "obs": "Occaecati aperiam quibusdam maxime laboriosam aperiam sint.",
        "created_at": "2017-03-20 02:29:47",
        "updated_at": "2017-03-20 02:29:47",
        "projects": {}
    }
]

Upvotes: 0

Views: 851

Answers (1)

sisve
sisve

Reputation: 19781

It sounds like you're never loading the relation. OneToMany-relations are lazily loaded by default.

You can trigger a loading by doing anything on it that would require a database call. A simple foreach would suffice in this example.

foreach($client->getProjects() as $project) {
    // ...
}

You could also configure the relation to be eager loaded. Source: 21.2.26. @OneToMany

/**
 * @OneToMany(..., fetch="EAGER")
 **/

This can also be a per-DQL-query. Source: 14.2.2. Joins

SELECT c, c.projects FROM Client c

Regarding the loading of Project.client, that could be the entity-map in action. You've already loaded the client from the entity manager, so when a Project instance says "I have client_id = 1" your entity manager notes that Client #1 is already loaded, and associates that with the Project.client relation.

The other way isn't possible since there is no way for Doctrine to know that you've loaded all possible projects that a client can have. The only true way to find out is to query the database.

Upvotes: 1

Related Questions