【发布时间】:2018-12-09 12:05:25
【问题描述】:
感谢 symfony 文档 https://symfony.com/doc/current/doctrine.html#updating-an-object,我能够从我的名为“Produit”的实体中使用 get/set 方法。
但是当我调用 setProduit() 方法(来自 Paniers 实体)时,Phpstorm 对 $produitSelected 说“预期的 App\Entity\Paniers,得到了对象”。
我不知道为什么 phpstorm 这么说,因为我可以使用方法,有什么问题? find() 返回一个实体对象,对吧?
class PaniersController extends AbstractController
{
/**
* @Route("/paniers/add/{id}", name="paniers.add")
*/
public function addPanier(Request $request, Environment $twig, RegistryInterface $doctrine, $id)
{
$produitSelected = $doctrine->getRepository(Produit::class)->find($id);
if (!$produitSelected) {
throw $this->createNotFoundException(
'Pas de produit trouvé pour l\' id : '.$id
);
}
$lignePanier=$doctrine->getRepository(Paniers::class)->findOneBy(['produit' => $produitSelected, 'user' =>$this->getUser()]);
if($produitSelected->getStock()>0){
if ($lignePanier){
$quantite =$lignePanier->getQuantite();
$lignePanier->setQuantite($quantite+1);
} else {
$lignePanier = new Paniers();
$lignePanier->setUser($this->getUser())
->setDateAjoutPanier(new \DateTime(date('Y-m-d')))
->setQuantite(1)
->setProduit($produitSelected);
}
$doctrine->getManager()->persist($lignePanier);
$produitSelected->setStock($produitSelected->getStock()-1);
$doctrine->getManager()->persist($produitSelected);
$doctrine->getManager()->flush();
}
}
}
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\PaniersRepository")
* @ORM\Table(name="paniers")
*/
class Paniers
{
//...
/**
* @ORM\ManyToOne(targetEntity="Produit")
* @ORM\JoinColumn(name="produit_id", referencedColumnName="id")
*/
private $produit;
public function getProduit(): ?Produit
{
return $this->produit;
}
public function setProduit(?Produit $produit): self
{
$this->produit = $produit;
return $this;
}
}
【问题讨论】:
标签: php symfony controller entity symfony4