Set value for the primay key with strategy set to NONE

巧了我就是萌 提交于 2020-01-02 14:39:33

问题


I have an Entity class that looks like this:

<?php

namespace Entities;

/** @Entity @Table(name="User") */
class User
{
    /**
     * @Id
     * @Column(type="string", length=12)
     */
    private $no;

Based on Doctrine 2 Identifier Generation Strategy section:

NONE: Tells Doctrine that the identifiers are assigned (and thus generated) by your code. The assignment must take place before a new entity is passed to EntityManager#persist. NONE is the same as leaving off the @GeneratedValue entirely.

That means, I need a way so that I can set the value before calling persist.

Calling ./doctrine orm:generate-entities wouldn't generate a setter function, do I have to write it manually in the class?

/**
 * Set no
 *
 * @param string $no
 */
public function setNo($no)
{
    $this->no = $no;
}

Is this the correct way to do it?


回答1:


There is no "correct" way to do this. the Generate-entities command is just a helper. Nothing that you HAVE to use. You can do as you please.

The only requirement with the assigned strategy is, that the id field has to be non-null when $em->persist() is called.

For example in the case of an assigned ID it makes sense to make it a required parameter in the constructor:

class User
{
    private $no;
    public function __construct($no)
    {
        $this->no = $no;
    }
}


来源:https://stackoverflow.com/questions/4291120/set-value-for-the-primay-key-with-strategy-set-to-none

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!