James May
James May

Reputation: 1537

OneToMany relationship in Symfony3 and Doctrine

I have one-to-many relationship, it's Currency with many Rates. So I define them as I read from manual:

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

But it seems I can't just assign Currency model to the property $this->currency, because Doctrine think it's some primitive like int, and just inserts {} into the query.

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

If I change the field to currency_id and return int from getter - it's fine, but how could I in this case the the related Currency model (I mean $rate->getCurrency()->something)? Of course I can implement Currency::__toString but looks like awful idea.

Upvotes: 0

Views: 41

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15686

Remove @ORM\Column annotation:

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

Doctrine will figure it out what should be the type of this column basing on referencedColumnName declared in @ORM\JoinColumn.

Upvotes: 3

Related Questions