Symfony2 OneToMany关系

时间:2017-09-01 10:03:07

标签: symfony doctrine-orm

我正在使用Symfony 2.5和PHP 5.3进行AdvertPlatform。

我想添加一项功能:当用户看到(通过点击它)广告时,我们可以看到文字"Seen by : {{username}}"

我开始在AdvertReaderAdvert之间添加一个新的实体nammed AdvertReader,其关系为OneToMany:

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

我的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 - &gt; [Mapping] OK [数据库]确定

  

Error500 ORM异常:在Association \ PerfclientBundle \ Entity \ AdvertReader#advert上找到类型的实体,但期望社会\ PerfclientBundle \ Entity \ Advert

     

堆栈跟踪分析器:    UnitOfWork - &gt; computeAssociationChanges(数组(&#39; fieldName&#39; =&gt;&#39;广告&#39;,&#39; joinColumns&#39; =&gt;数组(数组(&#39;名称&#39; ; =&gt;&#39; advert_id&#39;,&#39; unique&#39; =&gt; false,&#39; nullable&#39; =&gt; true,&#39; onDelete&#39; =&gt; null,&#39; columnDefinition&#39; =&gt; null,&#39; referencedColumnName&#39; =&gt;&#39; id&#39;)),&#39; cascade&#39; =&gt; array( ),&#39; inversedBy&#39; =&gt;&#39;读者&#39; targetEntity&#39; =&gt;&#39;社会\ PerfclientBundle \ Entity \ Advert&#39;,&# 39; fetch&#39; =&gt;&#39; 2&#39;,&#39;输入&#39; =&gt;&#39; 2&#39;,&#39; mappedBy&#39; =&gt; null ,&#39; isOwningSide&#39; =&gt; true,&#39; sourceEntity&#39; =&gt;&#39; Society \ PerfclientBundle \ Entity \ AdvertReader&#39;,&#39; isCascadeRemove&#39; =&gt; ; false,&#39; isCascadePersist&#39; =&gt; false,&#39; isCascadeRefresh&#39; =&gt; false,&#39; isCascadeMerge&#39; =&gt; false,&#39; isCascadeDetach&#39; =&gt; false,&#39; sourceToTargetKeyColumns&#39; =&gt;数组(&#39; advert_id&#39; =&GT; &#39; id&#39;),&#39; joinColumnFieldNames&#39; =&GT;数组(&#39; advert_id&#39; =&gt;&#39; advert_id&#39;),&#39; targetToSourceKeyColumns&#39; =&GT;数组(&#39; id&#39; =&gt;&#39; advert_id&#39;),&#39; orphanRemoval&#39; =&GT; false),&#39; 26&#39;)

我的实体关系出了什么问题? 请帮帮我:)。

1 个答案:

答案 0 :(得分:2)

我认为问题来自这段代码

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

请改为尝试:

$advertReader->setAdvert($advert);

Doctrine期望在该关系上有一个对象,而是传递一些整数。

希望这会有所帮助。快乐的编码

Alexandru Cosoi