vaultboy
vaultboy

Reputation: 139

Symfony 2.8 Doctrine fetch/display data trouble

Following the Symfony 2.8 book examples for the most part, as a total beginner I'm having trouble fetching data from the database with a ManyToOne relationship. I have a database table categories and one deploys. deploys has a category_id which refers to categories.id. So one category can have many deploys. The database has data, when I custom query in pma I get results.

My Question: After executing my controller code I get a Collection (see image), but not filled with deploy elements as it seems. What am I doing wrong? How can I display the deploy elements with a certain category_id

In my Controller I do:

$category = $this->getDoctrine()->getRepository('AppBundle:Category')->find(1);      
$deploys = $category->getDeploys();      
dump($deploys);
die();

This will display: enter image description here

I have a Deploy Entity: (part of it, it has been generated by app/console)

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="deploys")
 */
class Deploy {

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

  /**
   * @ORM\ManyToOne(targetEntity="Category", inversedBy="deploys")
   * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
   */
  private $category;
  // etc

And a Category Entity:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="categories")
 */
class Category {

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

  /**
   * @ORM\Column(type="string", length=255)
   */
  private $name;

  /**
   * @ORM\Column(type="integer", length=10)
   */
  private $weight;

  /**
   * @ORM\OneToMany(targetEntity="Deploy", mappedBy="category")
   */
  private $deploys;

   /**
   * Constructor
   */
  public function __construct() {
    $this->deploys = new ArrayCollection();
  }

  // etc

Upvotes: 0

Views: 272

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

This is lazy loading feature. They will be loaded form DB once you'll try to access them.

Try to simply access some elements of this collection (e.g. iterate over $deploys) and you will see it will work just fine.

Note that on your screen there is attribute initialized: false. That means that this collection was not accessed yet, so Doctrine didn't have to load it.

Upvotes: 3

Related Questions