0

I'm new in Symfony, and I am trying to calculate the average of the customer reviews at the controller level.

I did a dump in the foreach shown below, where I have the entity as I want, but in the return of the postman the field I added does not exist in my object.

nb: I don't have this field in my user table

My controller:

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);

}

and I add this in my entity:

private $reviewsuservalue;

and this is my getter & setter in the mentioned entity

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

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

    return $this;
}
S. Dre
  • 647
  • 1
  • 4
  • 18
  • 2
    So, do you have this in you doctrine entity, but not in your DB, right? If so, it won't be showed (nor added) in your db. If your DB does not have that column, Symfony will show an exception and complain about you trying to flush to a column that does not exist. – S. Dre Apr 20 '22 at 06:42

1 Answers1

0

Please try to use SerializerInterface & AbstractNormalizer;

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