Suppose you have a Log
and a LogDetalhe
table. First of all you will create the entities that will be mapped to the corresponding tables:
Table Log
:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Log
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="LogDetalhe", mappedBy="log")
*/
protected $logDetalhes;
public function __construct()
{
$this->logDetalhes = new ArrayCollection();
}
public function getLogDetalhes()
{
return $this->logDetalhes;
}
public function addLogDetalhe(LogDetalhe $logDetalhe)
{
$this->logDetalhes->add($logDetalhe);
return $this;
}
public function removeLogDetalhe(LogDetalhe $logDetalhe)
{
$this->logDetalhes->remove($logDetalhe);
return $this;
}
}
Table LogDetalhe
:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class LogDetalhe
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Log", inversedBy="logDetalhes")
* @ORM\JoinColumn(nullable=false)
*/
protected $log;
public function getLog()
{
return $this->log;
}
public function setLog(Log $log)
{
$this->log = $log;
return $this;
}
}
Note that the relationship is bidirectional because not only do I want to get the details from the log, but I want to get the log from a specific detail.
Then, to create a log and its corresponding details, it would be enough to do it like this:
$log = new Log();
$this->manager->persist($log);
$logDetalhe1 = (new LogDetalhes())->setLog($log);
$this->manager->persist($logDetalhe1);
$logDetalhe2 = (new LogDetalhes())->setLog($log);
$this->manager->persist($logDetalhe2);
$logDetalhe3 = (new LogDetalhes())->setLog($log);
$this->manager->persist($logDetalhe3);
$this->manager->flush();
See that Log
was first created, and then listed several entities of type LogDetalhe
to the first. Each of these entities must be persisted through EntityManager
of Doctrine, and then be saved to the bank by the flush()
method.