Zorrocaesar
Zorrocaesar

Reputation: 748

Weird issue with related entity in Doctrine

I'm using Doctrine2 inside Symfony and I have the following setup:

An Item class:

/**
 * Class Item
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\ItemRepository")
 */
class Item
{
    /**
     * @ORM\ManyToOne(targetEntity="Category")
     * @ORM\JoinColumn(name="primaryCategory", referencedColumnName="foreignId")
     */
    private $primaryCategory;
}

And a Category class:

/**
 * Category
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\CategoryRepository")
 */
class Category
{

    /**
     * @var integer
     *
     * @ORM\Column(name="foreignId", type="integer", unique=true)
     */
    private $foreignId;
}

Now when I do this:

$item = new Item();
$item->setPrimaryCategory($category);
$this->em->persist($item);
$this->em->flush();

I get this error:

[Symfony\Component\Debug\Exception\ContextErrorException] Notice: Undefined index: foreignId in home/www/project/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 692

Now, I've been looking at this from all angles and still cannot see what is wrong with this code. Can you help?

Upvotes: 1

Views: 3774

Answers (2)

Zorrocaesar
Zorrocaesar

Reputation: 748

After some more digging I figured out myself by using doctrine:schema:validate:

[Mapping] FAIL - The entity-class 'Acme\CommonBundle\Entity\Item' mapping is invalid: * The referenced column name 'foreignId' has to be a primary key column on the target entity class 'Acme\CommonBundle\Entity\Category'.

[Database] FAIL - The database schema is not in sync with the current mapping file.

So, I changed the foreign key from foreignId to id (which happens to be the primary key) and it works. I could, of course, just use foreignId as a primary key, but I realized actually I don't need that.

Upvotes: 3

drymek
drymek

Reputation: 335

Take a look at http://symfony.com/doc/current/book/doctrine.html#relationship-mapping-metadata.

You should rather have:

/**
 * Class Item
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\ItemRepository")
 */
class Item
{
    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="items")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $primaryCategory;
}

and:

/**
 * Category
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\CategoryRepository")
 */
 class Category
 {
     /**
      * @ORM\OneToMany(targetEntity="Item", mappedBy="primaryCategory")
      */
      private $items;
 }

Forget ID in ORM.

Upvotes: 0

Related Questions