Symfony2 OneToMany relation



我正在使用Symfony 2.5和PHP 5.3。

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

我开始添加一个新的实体nammed AdvertReader,在 AdvertAdvertReader之间具有关系onetomany:

广告:

    /**
     * Advert
     *
     * @ORMTable()
     * @ORMEntity(repositoryClass="SocietyPerfclientBundleEntityAdvertRepository")
     * @ORMHasLifecycleCallbacks()
     * @UniqueEntity(fields="title", message="Une annonce existe déjà avec ce titre.")
     */        
    class Advert
    {
        public function __construct()
        {
            $this->date = new Datetime();
        }
    /**
     *
     * @ORMOneToMany(targetEntity="SocietyPerfclientBundleEntityAdvertReader", mappedBy="advert", cascade={"persist"})
     */
    private $readers;

    /**
     * @var integer
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @var DateTime
     *
     * @ORMColumn(name="date", type="datetime")
     */
    private $date;
    /**
 * @var string
 *
 * @ORMColumn(name="title", type="string", length=255, unique=true)
 *
 * @AssertLength(min=10, minMessage="Le titre de l'annonce doit faire au moins {{ limit }} caractères.")
 */
    private $title;
    /**
     * @var string
     *
     * @ORMColumn(name="category", type="string", length=255)
     */
    private $category;
    /**
     * @var string
     *
     * @ORMColumn(name="author", type="string", length=255)
     */
    private $author;
    /**
     * @var string
     *
     * @ORMColumn(name="content", type="text")
     * @AssertLength(min=10, minMessage="Le contenu de l'annonce doit faire au moins {{ limit }} caractères.")
     */
    private $content;
    /**
     * @ORMColumn(name="updated_at", type="datetime", nullable=true)
     */
    private $updatedAt;`

advertreader.php:

/**
 * AdvertReader
 *
 * @ORMTable()
 * @ORMEntity
 */
class AdvertReader
{
    /**
     * @var integer
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORMManyToOne(targetEntity="SocietyPerfclientBundleEntityAdvert", inversedBy="readers")
     * @ORMJoinColumn(name="advert_id", referencedColumnName="id")
     */
    private $advert;
    /**
     * @var string
     *
     * @ORMColumn(name="username", type="string", length=255)
     */
    private $username;
    /**
     * @var DateTime
     *
     * @ORMColumn(name="created_at", type="datetime")
     */
    private $createdAt;
    /**
     * @var DateTime
     *
     * @ORMColumn(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;
    }

和我的视图()

    /**
     * @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,
        ));
    }

学说:架构:验证 - &gt;[映射]确定[数据库]确定

error500 orm异常:在协会社会中找到类型的实体 perfclientbundle entity advertreader#advert,但期望社会 perfclientbundle entity entity advarts advarts

堆叠跟踪剖面:unitofwork - &gt; computeassociationChanges(array('fieldName'=&gt;'广告','joincolumns'=&gt; array(array('name'=&gt'=&gt; advards_id','reasts_id','unique'unique'=&gt; false,nullable,'nullable'= nullable'='= nullable'=&gt; true,'onDelete'=&gt; null,'columndefinition'=&gt; null,'referencecolumnname'=&gt;'id'')),'cascade'=&gt; array(),'reversed'=&gt'=&gt;'读者','targinalentity'=&gt;'社会 perfclientbundle entity advarts','fetch'=&gt;'2','type'=&gt;'2','2','mappedby'=&gt; null,null,'isOnterings'=&gt; true,'sourceentity'=&gt;'社会 perfclientBundle entity advertreader','iScascadereMove'=&gt; false,'iscascadepersist'=&gt; false; false,'iscascaderefresh'iscascaderefresh'=&gt; forse,forse,'iscascademege'=&gt'=&gt'=&gt;'=&gt; array('id'=&gt;'advert_id'),'orphanremoval'=&gt; false),'26')

我的实体关系有什么问题?请帮助我:)

我认为问题来自该代码

的代码。
$advertReader->setAdvert($advert->getId());

而是尝试一下:

$advertReader->setAdvert($advert);

学说期望在该关系上有一个对象,而是通过一些整数。

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

Alexandru Cosoi

相关内容

  • 没有找到相关文章