symfony - Doctrine2 / MySQL - Create an auto increment field on multiple columns -
i wanted know if possible have auto increment field based on multiple columns ?
here problem : have table stores carts in lines. have unique id each carts want generate unique id each line. can have unique cart id inside line.
actually, want same in example mysql doc :
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 | +--------+----+---------+
the id increments within grp column.
i'm bit lost primary key / index , don't know if have use these in order generate ids.
i tried add symfony entity, didn't generate new column id want.
* @orm\table(indexes={@orm\index(name="line_idx", columns={"line_id"})})
thanks help
alright, managed want, i'm not sure if it's best way here how did:
i added cart_id field :
/** * @var integer * * @orm\column(name="cart_id", type="integer", nullable=false) */ private $cart_id;
then, added unique contraint, sure unique :
* @orm\table(uniqueconstraints={@uniqueconstraint(name="cart_idx", columns={"line_id", "cart_id"})})
then, made repository function last cart_id given line (there manytoone relation between cart , line:
<?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(); } }
and :
$cart = new cart; $lastcartid = $em->getrepository('cmplatformbundle:cart')->getlastcartidforline($lineid); $cart->setcartid($lastcartid+1); $em->persist($cart);
it works, not sure if best way handle this. let me know if find better.
Comments
Post a Comment