感谢symfony doc 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;
}
}
3 回答
除了Denis V的正确答案,我想补充一点,您也可以像这样修改控制器:
这样,phpstorm也知道返回对象的类型,因为每个返回的对象都是在相应的存储库中提示的类型 .
PhpStorm显然不是那么聪明,在这种情况下
find($id)
的返回值的实际类型将是Produit
. 但你可以帮助它:要使其正常工作,您应该将
Produit
与完整命名空间一起使用,或者直接在类型提示中添加命名空间 .当然,这并不能保证或确保实际类型为
Produit
. 因此,如果您犯了错误,PhpStorm将错误地报告类型 .您首先需要修复代码:
不要注入$ id,你只需要输入你的实体:https://symfony.com/doc/current/best_practices/controllers.html#using-the-paramconverter
不要注入$ doctrine,使用
$em = $this->getDoctrine()->getManager();
不要注入$ twig,使用
return $this->render('...template', []);
使用英语,这是 always 规则 . 不仅其他人可以帮助您,而且因为Symfony了解它,当您开始使用表单集时,您将需要它:https://symfony.com/doc/current/form/form_collections.html
注入存储库,您将更容易自动完成和发现错误 . 使用```make:entity``命令,你会看到我的想法,很难解释 .