Question

I have Item entity:

/**
 * Item
 *
 * @ORM\Table(name="item")
 * @ORM\Entity
 */
class Item {
...
    /**
     * @var Unit
     * @ORM\Column(name="unitId", type="integer")
     * @ORM\ManyToOne(targetEntity="Unit", inversedBy="items")
     * @ORM\JoinColumn(name="unitId", referencedColumnName="id")
     */
    private $unit;
...
}

And Unit entity:

/**
 * Unit
 *
 * @ORM\Table(name="unit")
 * @ORM\Entity
 */
class Unit {
...
    /**
     * @var Item[]
     * @ORM\OneToMany(targetEntity="Item", mappedBy="unit")
     */
    private $items;
...
}

And a code like:

$item = $this->objectManager->getRepository('Application\Main\Entity\Item')->find($id);
$unitName = $item->getUnit()->getName();

Which produces error Fatal error: Call to a member function getName() on a non-object, what means that doctrine handles this field as simple field, not a relation field. What should I do to force Doctrine to use this field as a relationship? I have few entities with such issue, while other are working just fine. What is the reason?

Was it helpful?

Solution

vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/AnnotationDrive.php, lines 262-263:

// Field can only be annotated with one of:
// @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany

So, it seems that you cannot use relation annotations when using @Column and visa versa. I had to remove @Column annotation and add @JoinColumn annotation and it started to work as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top