Doctrine Relational Mapping

Doctrine Relational Mapping
Association Mapping

Instead of working with foreign key Doctrine always works with references and convert those references to foreign keys.
some points you have to understan like
- A reference to a single object is represented by a foreign key.
- A collection of objects is represented by many foreign keys pointing to the object holding the collection
- If object reference back to the Entity it's Bidirectional Mapping
- If entity only reference back to the Entity it's Unidirectional Mapping

TYPES OF MAPPING

  • ManyToOne - Many instances of the current Entity refer to One instance of the refered Entity.
  • OneToOne - One instance of the current Entity refers to One instance of the refered Entity.
  • OneToMany - One instance of the current Entity has Many instances (references) to the refered Entity.

Many-To-One

-A many-to-one association is the most common association between objects.
-in doctine mapping create in php Annotation. like Below Example
-A many-to-one association is the most common association between objects.
-in doctine mapping create in php Annotation. like Below

<?php
/** @Entity */
class User
{
    /**
    * Many Users have One Address.
    * @ManyToOne(targetEntity="Address")
    * @JoinColumn(name="address_id", referencedColumnName="id")
    */
    private $address;
}

/** @Entity */
class Address
{
    // ...
}

One-To-One

- Here is a one-to-one relationship between a Customer and a Cart.
- The Cart has a reference back to the Customer so it is bidirectional.

<?php
/** @Entity */
class Customer
{
    // ...
    /**
    * One Customer has One Cart.
    * @OneToOne(targetEntity="Cart", mappedBy="customer")
    */
    private $cart;
    // ...
}

/** @Entity */
class Cart
{
    // ...
    /**
    * One Cart has One Customer.
    * @OneToOne(targetEntity="Customer", inversedBy="cart")
    * @JoinColumn(name="customer_id", referencedColumnName="id")
    */
    private $customer;
    // ...
}

One-To-Many

A one-to-many association has to be bidirectional, unless you are using an additional join-table.
This is necessary, because of the foreign key in a one-to-many association being defined on the “many” side.
Doctrine needs a many-to-one association that defines the mapping of this foreign key.

<?php

use DoctrineCommonCollectionsArrayCollection;

/** @Entity */
class Product
{
    // ...
    /**
    * One Product has Many Features.
    * @OneToMany(targetEntity="Feature", mappedBy="product")
    */
    private $features;
    // ...
    public function __construct() {
         $this->features = new ArrayCollection();
    }
}

/** @Entity */
class Feature
{
    // ...
    /**
    * Many Features have One Product.
    * @ManyToOne(targetEntity="Product", inversedBy="features")
    * @JoinColumn(name="product_id", referencedColumnName="id")
    */
    private $product;
    // ...
}

Use this Link To Know More: Association Mapping