所以我目前正试图找到Doctrine/Symfony中列的SUM。
目前我有它,所以用户输入产品在一个嵌入的形式(配方嵌入'ProductRecipe'关联到产品(1-m-1))"ProductRecipe。数量*产品。单位成本=产品成本',这样就可以了。现在我需要计算"配方"。通过添加每个配方的所有'Productcost'并将其存储在recipecost的' recipe '表中。
我试着遵循这个例子http://docs.doctrine-project.org/en/2.1/cookbook/aggregate-fields.html但不能为生活让它工作。我所尝试的一切都会抛出错误。我试过prepersist, persist, get和set。当我尝试添加一个新食谱时,我目前的错误是:
An exception occurred while executing 'INSERT INTO Recipe (recipename,
recipedesc, recipeyeild, recipecost, created_at, updated_at, u_id) VALUES
(?, ?, ?, ?, ?, ?, ?)' with params ["test cost", "test", 1, null,
"2014-03-22 17:04:56", null, 3]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'recipecost'
cannot be null
很明显,要么计算foreach。productcost要么没有在持久化之前运行,要么根本没有运行。后者是我有一种感觉正在发生,因为即使在尝试运行它预持久化时,它仍然会带来相同的错误。
我现在拥有的是:
//配方实体
class Recipe
{
private $id;
private $recipecost;
protected $product;
public function __construct()
{
$this->product = new 'Doctrine'Common'Collections'ArrayCollection();
}
public function setRecipecost($recipecost)
{
$this->recipecost = $recipecost;
return $this;
}
public function getRecipecost()
{
$recipecost = null; // note to self try 0
foreach($this->product AS $productcost){
$recipecost += $productcost->getProduct(); //note to self try getProductcost
}
return $this->recipecost;
}
//ProductRecipe实体class ProductRecipe
{
private $id;
private $amount;
private $product;
private $recipe;
private $productcost;
public function setProductcost($productcost) {
$this->productcost = $productcost;
return $this;
}
public function getProductcost() {
return $this->productcost;
}
public function __construct($productcost= 0, $product= '') {
$this->productcost = $productcost;
$this->product = $product;
}
//This function turns Costunit(from Product table) to Productcost.
/**
* @ORM'PrePersist
*/
public function pc2amc() {
$am = $this->amount;
$cu = $this->product->getCostunit();
$productcost = $am * $cu;
$this->productcost = $productcost;
}
我希望我已经涵盖了所有内容,已经删除了大多数我认为不相关的代码。如果需要的话,乐意张贴更多。
已经修复了我的问题,
这个函数:
public function getRecipecost()
{
$recipecost = 0;
foreach($this->product AS $productcost){
$recipecost += $productcost->getProductcost();
}
return $this->recipecost;
}
应该是这样的:
public function setRecipecost() //Set not Get to store in DB
{
// $recipecost = 0; **Remove this line**
foreach($this->product AS $productcost){
$this->recipecost += $productcost->getProductcost(); //$recipecost now $this->recipecost.
}
return $this->recipecost;
}
和Recipe控制器:
public function createAction(Request $request)
{
$entity = new Recipe();
$product = new ProductRecipe(); //* Add this line *
$entity->getProduct()->add($product); //* Add this line *
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity->setUser($this->get('security.context')->getToken()->getUser());
$em->persist($product); //* Add this line *
$em->persist($entity);
$em->flush();
现在工作的梦想,希望这将对其他人在相同的洞使用