Search code examples
arrayssymfonyoopdoctrineentity

How can I output ManyToOne data with doctrine (Symfony 4)?


This is my entity "data":

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="App\Repository\DataRepository")
*/
class Data
{
  /**
  * @ORM\Id()
  * @ORM\GeneratedValue()
  * @ORM\Column(type="integer")
  */
  private $id;

  /**
  * @ORM\Column(type="string", length=10, unique=true)
  */
  private $uuid;



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



  /**
   * @ORM\ManyToOne(targetEntity="Fields")
   * @ORM\JoinColumn(name="field", referencedColumnName="id")
   */

  private $fields;



  public function getId(): ?int
  {
    return $this->id;
  }



  public function getContent()
  {
    return $this->content;
  }

  public function setContent($content)
  {
    $this->content = $content;
  }




  public function getUuid(): ?string
  {
    return $this->uuid;
  }

  public function setUuid(string $uuid): self
  {
    $this->uuid = $uuid;

    return $this;
  }


  public function getFields(): ?Fields
  {
    return $this->fields;
  }

  public function setFields(?Fields $fields): self
  {
    $this->fields = $fields;

    return $this;
  }


}

I am getting the data via doctrine:

$output = $this->em->getRepository(Data::class)->findAll();

The output:

array:2 [▼
  0 => Data {#7060 ▼
    -id: 1
    -uuid: "12345"
    -content: "blabla"
    -fields: Fields {#7164 ▼
      +__isInitialized__: false
      -id: 6
      -name: null
      -uuid: null
      -productgroup: null
      -type: null
       …2
    }
  }
  1 => Data {#7165 ▶}
]

The problem is, that the data of the ManyToOne "fields" captures only the id. But not the name or productgroup. It is all "null". But in my database it is not null.


Solution

  • This usually happen when you are dumping objects with relations. For checking that fields relation has not null values. Do this:

    dump($output[0]->getFields()->getName())