如何生成自定义代码symfony 2

时间:2014-06-02 06:20:12

标签: php symfony doctrine-orm

我正在使用带有教义的symfony 2。我想为产品表创建自定义ID。

例如:

产品代码 P1000-1 P1000-2 P1000-3

如何生成这个?

2 个答案:

答案 0 :(得分:2)

如果是连续的,您可以尝试@GeneratedValue

如果您需要更多灵活性,则必须使用自定义Id生成器。根据您的要求,创建一个扩展AbstractIdGenerator并实施generate()方法的类。

并在您的实体中使用以下注释。

 @ORM\GeneratedValue(strategy="CUSTOM")
 @ORM\CustomIdGenerator(class="\Some\Bundle\Util\CustomGenerator")
在Id字段上

,确保generate()方法返回的字段与字段中使用的类型相同。

答案 1 :(得分:0)

如何编写一小段自定义函数来检索最后插入的ID,然后添加' P1000 - '在id之前。见下文,

public function getLastInsertedId($entity)
{
    $em = $this->getDoctrine()->getManager();
    $result = $em->createQueryBuilder();
    $last_inserted_id = $result->select('MAX(p.id) as id')
            ->from($entity, 'p')
            ->getQuery()
            ->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);        
    return 'P1000-'.$last_inserted_id['id'];
}

希望这会有所帮助。 干杯!