Records being inserted in two tables between Entities with (Doctrine - Foreign Key)

Asked

Viewed 350 times

0

I have two tables, one States and another Customers. When entering the records in the two tables, an error is occurring, instead of entering the state reference in the foreign key of the table Customers, is inserting the new state record into the table States, and in the Customers table, this new state is inserted in place of the foreign key.

What I need is just insert into the table Customers in the field "estado_fk" 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 entity Customers

   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 entity States

  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;
}


}
  • Probably your bank is assigned the keys, see if there are any restrictions or rules mapped inside the bank.

  • Note that the customer entity is also mapping the state:
/**
 * Clientes
 *
 * @ORM\Table(name="clientes", indexes={@ORM\Index(name="estado_fk", columns={"estado_fk"})})
 * @ORM\Entity
 */ . I believe that when you enter the two records into the database, the mapped Doctrine checks the state’s foreign key and passes to the user you are registering on $cliente->setEstadoFk($estado); with user registration.

  • All right. Ivan, how do I check for keys? I created my table with the following code.

  • create table clients(id int Primary key auto_increment, name varchar(100), state_fk int);

  • create table states(id int Primary key auto_increment, Uf char(2), state varchar(30) );

  • alter table clients add Foreign key (estado_fk) REFERENCES states(id);

  • But what is the problem you want to fix? If you do not want to enter the status, boot the reference: this reference: alter table clientes add foreign key (estado_fk) REFERENCES estados(id);

  • alter table clientes drop constraint RegraDoEstado

  • to check the constraints of your bank: SELECT DISTINCT(constraint_name) 
FROM information_schema.table_constraints 
WHERE constraint_schema = 'seubanco' 
ORDER BY constraint_name ASC;

  • The id of the state I have "selected", I want to save in the Clients table (estado_fk) without changing anything in the Status table. Only he’s not "setting" the id I picked up, he’s bringing me a new id (like it’s an auto increment)

  • Ahhh, now I understand the problem, you better edit your question because it was not clear. Because you said "inserted a new record in the State table".

  • That’s the problem kkkk but I’ll better formulate the title

  • Just a detail, why are you passing the name of the state, if you just want to get the reference?

  • Actually, Ivan, I’m doing a lot of tests because I’m racking my brain with this.

  • because you don’t just pass the id 2 inside the setState

  • It is that it only accepts being an instance of States

  • You’re telling me that in setEstadoFk, he needs to receive the entity?

  • In your controller, you can put the path of namespaces used?

Show 13 more comments

1 answer

1


You can take the state entity this way:

//coloque o caminho completo... 'Base\Model\...'
$estadoEntity = $em->getRepository('\Clientes\Entity\Estado')->findOneBy(
                    array(
                      'id' => 2
                    )
                );

Or if you want to take it by name (Obs: if you’re going to use like, you have to query DQL):

$estadoEntity = $em->getRepository('\Clientes\Entity\Estado')->findOneBy(
                        array(
                          'nome' => 'Minas Gerais'
                        )
                    );
   $id_estado = $estadoEntity->getId();

To capture all entities:

$estadoEntity = $em->getRepository('\Clientes\Entity\Estado')->findAll(); 

And you can do something just like that, I think it also works:

 $estadoEntity =  $em->getRepository('\Clientes\Entity\Estado')
                  ->getId(2);
  • So man, now he’s even accepted only that he’s generating a new record in the state table. :/

  • Entities were generated with Doctrine via Git Bash. Whether the entity is incorrect?

  • Got it... after making the changes you reported I removed the $em->persist($status);

  • Oh cool! If my reply helped you, mark the green arrow there. Thank you.

  • I clicked on the arrow up! Vlw. Abc

  • @Danilomiguel, you need to validate the answer by giving an ok on it (it is below the arrows).

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.