在我Symfony的項目,我有這個實體命名Order.php
默認值:創建方法來生成前綴和實體自動increlmentation直接
<?php
namespace myApp\EntityBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Datetime;
/**
*
* @ORM\Table(name="`order`")
* @ORM\Entity(repositoryClass="myApp\EntityBundle\Repository\OrderRepository")
*
*/
class Order
{
/**
* @var integer
*
* @ORM\Column(name="order_id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* Command name ref for right accounting
*
* @var string
*
* @Assert\Type(
* type="string",
* message="The value {{ value }} is not a valid {{ type }}."
*)
* @Assert\NotNull()
* @Assert\NotBlank()
* @ORM\Column(name="order_name", type="string", length=255, nullable=true, unique=true)
*/
protected $orderName;
// etc other associations, object and getters setters...
/**
* Constructor
*/
public function __construct()
{
$this->generateOrderName();
}
/**
* generate order_name with base ref
*
* @return Order
*/
public function generateOrderName()
{
// trying to make the good practice for generated orderName value
//$now = new Datetime();
//$year = $now->format("Y");
//$month = $now->format("m");
//$orderNameCommon = $year."_".$month."_";
$this->setOrderName();
return $this;
}
/**
* Set orderName
*
* @param string $orderName
*
* @return Order
*/
public function setOrderName($orderName)
{
$this->orderName = $orderName;
return $this;
}
/**
* Get orderName
*
* @return string
*/
public function getOrderName()
{
return $this->orderName;
}
}
的目的是爲了產生這樣一個ORDERNAME:「2016_09_00001 '這意味着我按日期Year_Month_orderNumber註冊了訂單。
我必須注意,orderName必須是唯一的,例如,如果我已經有一個名爲'2016_09_00001'的訂單,我必須像這樣'2016_09_00002'註冊訂單名稱。例如,像自動增量一樣。
正如你所看到的,我已經直接在實體類訂單使這個代碼:
/**
* Constructor
*/
public function __construct()
{
// call the order name generation function
$this->generateOrderName();
}
/**
* generate order_name with base ref
*
* @return Order
*/
public function generateOrderName()
{
$now = new Datetime();
$year = $now->format("Y");
$month = $now->format("m");
$prefix = $year."_".$month."_";
// That I had planned:
// to create a prefix with Datetime argument, year and month
// Then check all order in database with this prefix
// Finally count the results and add +1 on the final value
$this->setOrderName();
return $this;
}
正如你所看到的,我已經叫在構造的generateOrderName()
功能,然後我想使這個過程:
添加+1我有計劃:
創建帶有日期時間的說法,年份和月份的前綴
然後以這個前綴檢查所有爲了在數據庫
最後計算的結果和最終值
什麼是直接在實體中正確使用它的最佳方法?我認爲在實體類本身中存儲庫dql查詢調用並不是一件好事。
我已創建這一個例子:
public function searchOrderName($prefix)
{
return
$this->getEntityManager()
->createQuery(
"SELECT o.orderName FROM EntityBundle:Order o
WHERE o.orderName
LIKE :prefix
ORDER BY o.id ASC"
)
->setParameter("prefix", $prefix.'%')
->getResult();
}
我如何可以繼續創建於實體generateOrderName()
功能使生成的過程中,我會直接喜歡實體類?