Symfony3和Doctrine中的OneToMany关系

时间:2017-06-28 09:33:32

标签: symfony doctrine-orm

我有一对多的关系,这是多种利率的货币。所以我在阅读手册时定义它们:

/**
 * @ORM\Table(name="currency")
 * @ORM\Entity
 */
class Currency{}

/**
 * @ORM\Table(name="rate")
 * @ORM\Entity
 */
class Rate
{
    /**
     * @ORM\Column(name="currency_id", type="integer")
     * @ORM\ManyToOne(targetEntity="Currency", inversedBy="rate")
     * @ORM\JoinColumn(name="currency_id", referencedColumnName="id")
     */
    private $currency;

    /**
     * @param  Currency $currency
     * @return Rate
     */
    public function setCurrency(Currency $currency) : Rate
    {
        $this->currency = $currency;
        return $this;
    }

    /**
     * @return Currency
     */
    public function getCurrency() : Currency
    {
        return $this->currency;
    }
}

但似乎我不能只将货币模型分配给属性 $ this->货币,因为Doctrine认为它像int一样原始,只是在查询中插入{}。

Object of class AppBundle\Entity\Currency could not be converted to string

如果我将字段更改为 currency_id 并从getter返回int - 那很好,但在这种情况下我怎么能使用相关的Currency模型(我的意思是 $ rate-> getCurrency () - >东西)?当然我可以实现Currency :: __ toString,但看起来很糟糕。

1 个答案:

答案 0 :(得分:3)

删除@ORM\Column注释:

 * @ORM\Column(name="currency_id", type="integer")

Doctrine会根据referencedColumnName中声明的@ORM\JoinColumn来确定该列的类型。