I want to set id manual I write this code in my Test entity:
can I use setId() for entities like my code?
My code is here:
/**
* Test
* @ORM\Table(name="test")
*/
class Test
{
/**
* @var int
* @ORM\Column(name="id", type="integer")
*/
private $id;
/**
* @var string
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Set id
* @param integer $id
* @return Test
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
* @return integer
*/
public function getId()
{
return $this->id;
}
// other methods
}
is this correct way to set id? if not what is the correct and standard way?
You can use your own primary key, telling to Doctrine not to generate value ...
https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_generatedvalue
/**
* Test
* @ORM\Table(name="test")
*/
class Test
{
/**
* @var int
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
* @ORM\Column(name="id", type="integer")
*/
private $id;
/**
* Set id
* @param integer $id
* @return Test
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
Don't forget setId before persist!
Doctrine expects the primary key of your entity to be immutable (non-changeable) after the entity is persisted/flushed to the database (or fetched from DB).
The code you wrote is perfectly correct in terms of PHP but will most likely break doctrine functionality if you ever use setId()
.
If you are interested in the internals, look up "Doctrine identity maps"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With