4

这个问题与我的另一个问题有关:Doctrine2 只给了我相关对象的第一个实例

我想出了双向关联来尝试解决我的旧问题,但现在我遇到了另一个问题。

架构[编辑]

  XYZ\Bundle\CitiesBundle\Entity\Cities:
  type: entity
  table: cities
  fields:
    id:
      id: true
      type: integer
      unsigned: false
      nullable: false
      generator:
        strategy: IDENTITY
    name:
      type: string
      length: 50
      fixed: false
      nullable: false
    landarea:
      type: decimal
      nullable: false
    density:
      type: integer
      unsigned: false
      nullable: false
    population:
      type: integer
      unsigned: false
      nullable: false
  manyToOne:
    state:
      targetEntity: States
      cascade: {  }
      inversedBy: cities
      joinColumn:
        state_id:
          referencedColumnName: id
  lifecycleCallbacks: {  }

实体:

class Cities
{
    //other vars

    /**
     * @var XYZ\Bundle\CitiesBundle\Entity\States
     */
    private $state;

    //other get/set    

    /**
     * Set state
     *
     * @param XYZ\Bundle\CitiesBundle\Entity\States $state
     */
    public function setState(\XYZ\Bundle\CitiesBundle\Entity\States $state)
    {
        $this->state = $state;
    }

    /**
     * Get state
     *
     * @return XYZ\Bundle\CitiesBundle\Entity\States 
     */
    public function getState()
    {
        return $this->state;
    }
}

class States
{
    //other vars and get/set

    private $cities;

    public function __construct()
    {
        $this->cities = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add cities
     *
     * @param XYZ\Bundle\CitiesBundle\Entity\Cities $cities
     */
    public function addCities(\XYZ\Bundle\CitiesBundle\Entity\Cities $cities)
    {
        $this->cities[] = $cities;
    }

    /**
     * Get cities
     *
     * @return Doctrine\Common\Collections\Collection 
     */
    public function getCities()
    {
        return $this->cities;
    }
}

查询生成器用法:

    $query = $em->createQueryBuilder()
                ->select('c','s')
                ->from('CitiesBundle:Cities', 'c')
                ->innerJoin('c.state', 's')
                ->orderBy('c.population', 'DESC')
                ->setMaxResults(10)
                ->getQuery();  

错误是:

[语义错误] line 0, col 58 near 's ORDER BY c.population': Error: Class XYZ\Bundle\CitiesBundle\Entity\Cities 没有名为 state 的关联

生成的 DQL:

SELECT c, s FROM CitiesBundle:Cities c INNER JOIN c.state s ORDER BY c.population DESC

耻辱:(

有人可以帮我解决我的问题吗?

[编辑]

我编辑了城市架构,现在错误是:

注意:未定义的索引:/home/marek/devel/sf2/cities/vendor/doctrine/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php 第 473 行中的名称

4

2 回答 2

2

我确定joinColumns:(注意复数)仅用于Many-To-Many关系。在其他关系中,您应该使用joinColumn.

在 Cities XML 中,尝试输入:

joinColumn:
    name: state_id
    referencedColumnName: id

除此之外,请尝试在您的 XML 中将“ManyToOne”重命名为“manyToOne”,但我怀疑这种情况是否是这里的问题......

希望这可以帮助...

于 2012-05-05T08:50:28.240 回答
2

请注意,当使用 Symfony 时,它会首先查看映射 YAML 文件并忽略您的实体注释。在加载 YAML 映射文件的过程中,我花了很长时间更改我的注释。

于 2013-10-02T21:12:03.743 回答