我想知道是否可以有一个基于多列的自动递增字段?
这是我的问题: 我有一个表,它在 LINES 中存储 CARTS。我为每个购物车都有一个唯一的 ID,但我也想为每一行生成一个唯一的 ID。所以我可以在一行中有一个唯一的 CART ID。
实际上,我想做的和 MySQL 文档中的这个例子完全一样:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
+--------+----+---------+
| grp | id | name |
+--------+----+---------+
| fish | 1 | lax |
| mammal | 1 | dog |
| mammal | 2 | cat |
| mammal | 3 | whale |
| bird | 1 | penguin |
| bird | 2 | ostrich |
+--------+----+---------+
id 在 grp 列内递增。
我对主键/索引有点迷茫,我不知道是否必须使用它们来生成我的 ID。
我试图将其添加到我的 symfony 实体中,但它没有生成具有我想要的 ID 的新列。
* @ORM\Table(indexes={@ORM\Index(name="line_idx", columns={"line_id"})})
最佳答案
好吧,我设法做了我想做的事,我不确定这是否是最好的方法,但我是这样做的:
我添加了我的 cart_id 字段:
/**
* @var integer
*
* @ORM\Column(name="cart_id", type="integer", nullable=false)
*/
private $cart_id;
然后,我添加了一个唯一约束,以确保所有内容都是唯一的:
* @ORM\Table(uniqueConstraints={@UniqueConstraint(name="cart_idx", columns={"line_id", "cart_id"})})
然后,我创建了一个存储库函数来获取给定行的最后一个 cart_id(我的购物车和我的行之间存在 ManyToOne 关系:
<?php
namespace CM\PlatformBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* CartRepository
*/
class CartRepository extends EntityRepository
{
public function getLastCartIdForLine($lineId) {
return $this->createQueryBuilder('c')
->select('c.cart_id')
->join('c.line','l')
->andWhere('l.id = :lineId')
->setParameter('lineId', $lineId)
->orderBy('c.id', 'DESC')
->setMaxResults(1)
->getQuery()
->getSingleScalarResult();
}
}
我终于做到了:
$cart = new Cart;
$lastCartId = $em->getRepository('CMPlatformBundle:Cart')->getLastCartIdForLine($lineId);
$cart->setCartId($lastCartId+1);
$em->persist($cart);
有效,但不确定这是否是处理此问题的最佳方式。如果您找到更好的东西,请告诉我。
关于mysql - Doctrine2/MySQL - 在多列上创建一个自动递增字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587155/