I have two tables, one States and another Customers . When inserting the records in the two tables, an error is occurring, instead of inserting the state reference in the foreign key of the Clients table, you are inserting the new status record in the States < strong>, and in the Customers table, this new state is inserted in place of the foreign key.
What I need to do is just insert the Customers table in the "state_fk" field the ID I got from the State without changing anything in the State table.
The Controller
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$estado = new \Clientes\Entity\Estados();
$estado->setId('2');
$estado->setEstado('Minas Gerais');
$cliente = new \Clientes\Entity\Clientes();
$cliente->setNome('MEU NOME É');
$cliente->setEstadoFk($estado);
$em->persist($estado);
$em->persist($cliente);
$em->flush();
die;
The Customers entity
namespace Clientes\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Clientes
*
* @ORM\Table(name="clientes", indexes={@ORM\Index(name="estado_fk", columns={"estado_fk"})})
* @ORM\Entity
*/
class Clientes
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nome", type="string", length=100, nullable=true)
*/
private $nome;
/**
* @var \Estados
*
* @ORM\ManyToOne(targetEntity="Estados")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="estado_fk", referencedColumnName="id")
* })
*/
private $estadoFk;
function getId() {
return $this->id;
}
function getNome() {
return $this->nome;
}
function getEstadoFk() {
return $this->estadoFk;
}
function setId($id) {
$this->id = $id;
}
function setNome($nome) {
$this->nome = $nome;
}
function setEstadoFk(\Clientes\Entity\Estados $estadoFk) {
$this->estadoFk = $estadoFk;
}
}
The States entity
namespace Clientes\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Estados
*
* @ORM\Table(name="estados")
* @ORM\Entity
*/
class Estados
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="uf", type="string", length=2, nullable=true)
*/
private $uf;
/**
* @var string
*
* @ORM\Column(name="estado", type="string", length=30, nullable=true)
*/
private $estado;
function getId() {
return $this->id;
}
function getUf() {
return $this->uf;
}
function getEstado() {
return $this->estado;
}
function setId($id) {
$this->id = $id;
}
function setUf($uf) {
$this->uf = $uf;
}
function setEstado($estado) {
$this->estado = $estado;
}
}