Symfony2 + Doctrine One-to-Many关系

时间:2012-07-03 15:52:39

标签: symfony doctrine

我正在尝试将Doctrine应用于在两个表之间具有OneToMany关系的现有数据库:Commerce和Area。 我从数据库生成了yml架构,结果如下:

Area:
  type: entity
  table: area
  fields:
    id:
      id: true
      type: integer
      unsigned: false
      nullable: false
      generator:
        strategy: IDENTITY
    name:
      type: string
      length: 255
      fixed: false
      nullable: true
  lifecycleCallbacks: {  }

Commerce:
  type: entity
  table: commerce
  fields:
    id:
      id: true
      type: integer
      unsigned: false
      nullable: false
      generator:
        strategy: IDENTITY
    name:
      type: string
      length: 255
      fixed: false
      nullable: true
  manyToOne:
    area:
      targetEntity: Area
      cascade: {  }
      mappedBy: null
      inversedBy: null
      joinColumns:
        area_id:
          referencedColumnName: id
      orphanRemoval: false
  lifecycleCallbacks: {  }

从该模式中我生成了实体:

use Doctrine\ORM\Mapping as ORM;

/**
 * Model\EntitiesBundle\Entity\Area
 *
 * @ORM\Table(name="area")
 * @ORM\Entity
 */
class Area
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

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


    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

}


use Doctrine\ORM\Mapping as ORM;

/**
 * Model\EntitiesBundle\Entity\Commerce
 *
 * @ORM\Table(name="commerce")
 * @ORM\Entity
 */
class Commerce
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

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

    /**
     * @var Area
     *
     * @ORM\ManyToOne(targetEntity="Area")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="area_id", referencedColumnName="id")
     * })
     */
    private $area;


    /**
     * @return \Model\EntitiesBundle\Entity\Area
     */
    public function getArea()
    {
        return $this->area;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}

我的问题来自于我尝试:

$commerce = $em->getRepository('ModelEntitiesBundle:Commerces')
               ->find($id);
echo $commerce->getArea()->getName();

Area实体具有空属性。 有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。它在其他地方,我有两个实体经理,我需要的不是默认的。