设置策略设置为NONE的主键的值 [英] Set value for the primay key with strategy set to NONE

查看:218
本文介绍了设置策略设置为NONE的主键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体类,如下所示:

 <?php 

命名空间实体;

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

根据Doctrine 2识别码生成策略部分:



NONE:告诉您的代码,
标识符被分配(从而
生成)。
赋值必须在
新实体传递给
EntityManager#persist之前进行。 NONE是
相同的,完全离开
@GeneratedValue。


这意味着,我需要一种方式所以我可以在调用持久化之前设置值。



调用 ./ doctrine orm:generate-entities t生成setter函数,我必须在类中手动写入吗?

  / ** 
*设置否
*
* @param string $ no
* /
public function setNo($ no)
{
$ this-> no = $没有;
}

这是正确的方法吗?

解决方案

没有正确的方法来做到这一点。 Generate-entities命令只是一个帮手。没有什么你可以使用。你可以随便做。



分配策略的唯一要求是,当$ em-> persist()为



例如,在分配的ID的情况下,将其设置为构造函数中必需的参数是有意义的:

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


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?

解决方案

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

这篇关于设置策略设置为NONE的主键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆