khernik
khernik

Reputation: 2091

One to many relationship mapping

I have two entities - shop and product. One shop can have many products, but one product always has just one shop.

class Shop {
/**
     * @var integer
     *
     * @ORM\Column(name="shop_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $shopId;
/**
     * @var \Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Product", mappedBy="shop")
     */
    private $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }
}

class Product {
/**
     * @var integer
     *
     * @ORM\Column(name="product_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $productId;

    /**
     * @ORM\ManyToOne(targetEntity="Shop", inversedBy="products")
     * @ORM\JoinColumn(name="shop_id", referencedColumnName="product_id")
     */
    private $shop;
}

When I run the website I however get the notice error that product_id is an undefined index in vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1778. What's wrong?

Upvotes: 1

Views: 126

Answers (2)

vita
vita

Reputation: 63

You don't have a product_id column in the shop table. I think your shop_id column name may also be causing a conflict with the referenceColumnName value. So change the shop id column name to just Id.

Then Change the referenceColumnName to just (the shops) id.

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $shopId;

/**
 * @ORM\ManyToOne(targetEntity="Shop", inversedBy="products")
 * @ORM\JoinColumn(name="shop_id", referencedColumnName="id")
 */
private $shop;

Upvotes: 0

Roman  Kliuchko
Roman Kliuchko

Reputation: 499

Probably you need to reference to shopId field in your Product entity. Also notice that you should use entity properties' names, not names of the columns in you DB table.

/**
 * @ORM\ManyToOne(targetEntity="Shop", inversedBy="products")
 * @ORM\JoinColumn(name="shop_id", referencedColumnName="shopId")
 */
private $shop;

P.S. For mapping issues Symfony command doctrine:schema:validate may be useful.

Upvotes: 1

Related Questions