Symfony2 OneToMany relation

2019-06-13 15:57发布

I'm doing an AdvertPlatform with Symfony 2.5 and PHP 5.3.

I want to add a feature that is : when a user see(by clicking on it) an advert, we can see a text "Seen by : {{username}}".

I started add a new Entity nammed AdvertReader with a relation OneToMany between Advert and AdvertReader:

Advert.php:

    /**
     * Advert
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="Society\PerfclientBundle\Entity\AdvertRepository")
     * @ORM\HasLifecycleCallbacks()
     * @UniqueEntity(fields="title", message="Une annonce existe déjà avec ce titre.")
     */        
    class Advert
    {
        public function __construct()
        {
            $this->date = new \Datetime();
        }

    /**
     *
     * @ORM\OneToMany(targetEntity="Society\PerfclientBundle\Entity\AdvertReader", mappedBy="advert", cascade={"persist"})
     */
    private $readers;


    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="datetime")
     */
    private $date;

    /**
 * @var string
 *
 * @ORM\Column(name="title", type="string", length=255, unique=true)
 *
 * @Assert\Length(min=10, minMessage="Le titre de l'annonce doit faire au moins {{ limit }} caractères.")
 */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="category", type="string", length=255)
     */
    private $category;

    /**
     * @var string
     *
     * @ORM\Column(name="author", type="string", length=255)
     */
    private $author;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="text")
     * @Assert\Length(min=10, minMessage="Le contenu de l'annonce doit faire au moins {{ limit }} caractères.")
     */
    private $content;

    /**
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     */
    private $updatedAt;`

AdvertReader.php :

/**
 * AdvertReader
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class AdvertReader
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Society\PerfclientBundle\Entity\Advert", inversedBy="readers")
     * @ORM\JoinColumn(name="advert_id", referencedColumnName="id")
     */
    private $advert;

    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=255)
     */
    private $username;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime")
     */
    private $updatedAt;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set advert
     *
     * @param integer $advert
     * @return AdvertReader
     */
    public function setAdvert($advert)
    {
        $this->advert = $advert;

        return $this;
    }

    /**
     * Get advert
     *
     * @return integer 
     */
    public function getAdvert()
    {
        return $this->advert;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return AdvertReader
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string 
     */
    public function getUsername()
    {
        return $this->username;
    }

And my viewAction()

    /**
     * @param $id
     * @return Response
     */
    public function viewAction($id)
    {
        // On récupère le repository
        $repository = $this->getDoctrine()
            ->getManager()
            ->getRepository('SocietyPerfclientBundle:Advert')
        ;
        $advert = $repository->find($id);

        if (null === $advert) {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        $securityContext = $this->container->get('security.context');
        $user = $securityContext->getToken()->getUser();

        if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
            $em = $this->getDoctrine()->getManager();
            $queryBuilder = $em->createQueryBuilder();

            $query = $queryBuilder->select('count(ar.id)')
                ->from('SocietyPerfclientBundle:AdvertReader', 'ar')
                ->where('ar.advert = :advert')
                ->andWhere('ar.username = :username')
                ->setParameter('advert', $advert->getId())
                ->setParameter('username', $user->getUsername())
                ->getQuery();

            $advertReaderCount = $query->getSingleScalarResult();

            if ($advertReaderCount <= 0) {
// l'utilisateur lis pour la 1er fois
                $advertReader = new AdvertReader;
                $advertReader->setAdvert($advert->getId());
                $advertReader->setUpdatedAt(new \DateTime);
                $advertReader->setUsername($user->getUsername());
                $advertReader->setCreatedAt(new \DateTime);

                $em->persist($advertReader);
                $em->flush();
            }
        }

        return $this->render('SocietyPerfclientBundle:Default:view.html.twig', array(
            'advert' => $advert,
        ));
    }

doctrine:schema:validate -> [Mapping] OK [Database] OK

Error500 ORM Exception : Found entity of type on association Society\PerfclientBundle\Entity\AdvertReader#advert, but expecting Society\PerfclientBundle\Entity\Advert

Stack Trace Profiler : UnitOfWork ->computeAssociationChanges (array('fieldName' => 'advert', 'joinColumns' => array(array('name' => 'advert_id', 'unique' => false, 'nullable' => true, 'onDelete' => null, 'columnDefinition' => null, 'referencedColumnName' => 'id')), 'cascade' => array(), 'inversedBy' => 'readers', 'targetEntity' => 'Society\PerfclientBundle\Entity\Advert', 'fetch' => '2', 'type' => '2', 'mappedBy' => null, 'isOwningSide' => true, 'sourceEntity' => 'Society\PerfclientBundle\Entity\AdvertReader', 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'sourceToTargetKeyColumns' => array('advert_id' => 'id'), 'joinColumnFieldNames' => array('advert_id' => 'advert_id'), 'targetToSourceKeyColumns' => array('id' => 'advert_id'), 'orphanRemoval' => false), '26')

What's wrong with my entity relation ? Please help me :)

1条回答
Viruses.
2楼-- · 2019-06-13 16:22

I think the problem comes from this code piece of code

$advertReader->setAdvert($advert->getId());

Try this instead:

$advertReader->setAdvert($advert);

Doctrine is expecting an object on that relation and instead you pass some integer.

Hope this helps. Happy coding

Alexandru Cosoi

查看更多
登录 后发表回答