A.Seddighi
A.Seddighi

Reputation: 1765

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?

Upvotes: 6

Views: 11178

Answers (2)

SilvioQ
SilvioQ

Reputation: 2072

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!

Upvotes: 9

Xymanek
Xymanek

Reputation: 1389

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"

Upvotes: 3

Related Questions