Doctrine 2 Association Mapping(ManyToOne和OneToMany)

时间:2013-12-20 13:48:00

标签: doctrine-orm zend-framework2

我是Doctrine2的新手,需要一些帮助。 我有2个实体:LocationEntity和RatingEntity RatingEntity

<?php

use Doctrine\ORM\Mapping as ORM;

/**
 * Rating
 *
 * @ORM\Entity
 * @ORM\Table(name="`RATING`")
 */
class RatingEntity {

    /**
     *
     * @var int
     * @ORM\Id
     * @ORM\Column(name="`ID`", type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="RATING_ID_SEQ", initialValue=1, allocationSize=1)
     */
    protected $id;

    /**
     *
     * @var int
     * @ORM\Column(name="`LOCATION_ID`", type="integer")
     */
    protected $locationId;

    /**
     * @var LocationEntity
     * @ORM\ManyToOne(targetEntity="LocationEntity", inversedBy="ratings")
     * @ORM\JoinColumn(name="`LOCATION_ID`", referencedColumnName="`ID`")
     */
    protected $location;

    /**
     * @return the $location
     */
    public function getLocation() {
        return $this->location;
    }

    /**
     * @param field_type $location
     */
    public function setLocation($location) {
        $this->location = $location;
    }

LocationEntity

<?php       

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * Location
 *
 * @ORM\Entity
 * @ORM\Table(name="`LOCATION`")
 */
class LocationEntity {

    /**
     *
     * @var int
     * @ORM\Id
     * @ORM\Column(name="`ID`", type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="LOCATION_ID_SEQ", initialValue=1, allocationSize=1)
     */
    protected $id;            

    /**
     *
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="RatingEntity", mappedBy="location", cascade={"persist"}, fetch="LAZY")
     */
    protected $ratings;

    /**
     * @return the $ratings
     */
    public function getRatings() {

        return $this->ratings;
    }

    /**
     * @param \Doctrine\Common\Collections\ArrayCollection $ratings
     */
    public function setRatings($ratings) {

        $this->ratings = $ratings;
    }

    /**
     * Never forget to initialize all your collections!
     */
    public function __construct() {
        $this->ratings = new ArrayCollection();
    }

如果我获得位置,我会将位置评级为数组, 但如果我想得到它的评级和位置,我只在getLocation()中得到NULL。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我认为您的Rating实体中不需要locationId属性,因为已使用location属性映射列。尝试删除locationId部分,看看它是否无法按预期工作。