使用控制器中的新字段更新实体- Symfony 6

o75abkj4  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(120)

我是新来的Symfony,我正试图计算控制器级别的客户评论的平均值。
我在foreach中做了一个转储,如下所示,在那里我有我想要的实体,但是在postman的返回中,我添加的字段在我的对象中不存在。
nb:我的用户表中没有此字段

我的控制器:

public function __invoke(UserRepository $rep, Request $request , EntityManagerInterface $em)

{

    $user = $this->get('security.token_storage')->getToken()->getUser();

    $dataUser = $rep->findUsersData();
    $Reviews = $rep->findUsersReviews($user->getId());
    $countReviews = count($Reviews);
    $starsValues = 0;
    foreach($Reviews as $review){
        //dump($review);
        $starsValues += $review['stars'];
    }
    $reviewsuservalue = $starsValues / $countReviews;

    foreach($dataUser as $key => $userForeach){
        if($userForeach->getId() == $user->getId()){
            $userForeach->setReviewsuservalue($reviewsuservalue);
            //dump($dataUser[$key]->getReviewsuservalue());
            $em->persist($userForeach);
            $em->flush();
            //dump($em->flush());
        }
    }

    return $this->json($dataUser);

}

我把这个加到我的实体:

private $reviewsuservalue;

这是我在上述实体中的getter & setter

public function getReviewsuservalue(): ?float
{
    return $this->reviewsuservalue;
}

public function setReviewsuservalue(float $reviewsuservalue): self
{
    $this->reviewsuservalue = $reviewsuservalue;

    return $this;
}
toe95027

toe950271#

请尝试使用串行化接口和抽象规范化;

use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
$new_variable = $serializer->normalize($userForeach, null, [
            AbstractNormalizer::ATTRIBUTES => ['id', 'otherAttribute' , ...],
        ]);
    return $new_variable;

相关问题