Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is possible use setId() for id in doctrine entity?

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?

like image 446
A.Seddighi Avatar asked Jan 03 '23 13:01

A.Seddighi


2 Answers

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!

like image 120
SilvioQ Avatar answered Jan 09 '23 19:01

SilvioQ


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"

like image 22
Xymanek Avatar answered Jan 09 '23 20:01

Xymanek