170 likes | 269 Views
Symfony2 - Step-by-step. Doctrine ORM Relationship OneToOne ManyToOne OneToMany ManyToMany Self-referencing. Entities. OneToOne. “Blog” vs “Blog Setting” 1 blog has only 1 setting 1 setting only belong to 1 blog. /** @Entity **/ class Blog { // ... /**
E N D
Symfony2 - Step-by-step • Doctrine ORM Relationship • OneToOne • ManyToOne • OneToMany • ManyToMany • Self-referencing
OneToOne • “Blog” vs “Blog Setting” • 1 blog has only 1 setting • 1 setting only belong to 1 blog
/** @Entity **/ class Blog { // ... /** * @OneToOne(targetEntity=“BlogSetting") * @JoinColumn(name=“setting_id", referencedColumnName="id") **/ private $setting; // ... } /** @Entity **/ class BlogSetting { // ... }
Tables • Blog • BlogSetting
ManyToOne and OneToMany • “Blog” vs “Post” • 1 blog has many posts • 1 post only belong to 1 blog
/** @Entity **/ class Blog { // ... /** * @ORM\OneToMany(targetEntity="Post", mappedBy="blog", cascade={"remove"}) **/ private $posts; // ... } /** @Entity **/ class Post { /** * @ORM\ManyToOne(targetEntity=“Blog", inversedBy="posts“) * @ORM\JoinColumn(name="blog_id", referencedColumnName="id") **/ private $blog; }
Tables • Blog • Post
ManyToMany • “Post” vs “Category” • 1 post can belong to one or many categories • 1 category can have one or many posts 1. Post “Singapore tour” 2. Post category “tour”, “relax”, “picture” 3. Post “Nhatrang tour” 4. Post category “tour”
/** @Entity **/ class Post { // ... /** * @ORM\ManyToMany(targetEntity="Category", inversedBy="posts") * @ORM\JoinTable(name="category_post") **/ private $categories; // ... } /** @Entity **/ class Category { /** * @ORM\ManyToMany(targetEntity="Post", mappedBy="categories") **/ private $posts; }
Tables • Category • Post • Category_Post
OneToMany – Self-referencing • “Category” vs “Parent Category” • 1 category has 1 parent category • 1 parent category has 1 or many children category
/** @Entity **/ class Category { // ... /** * @OneToMany(targetEntity="Category", mappedBy="parent") **/ private $children; /** * @ManyToOne(targetEntity="Category", inversedBy="children") * @JoinColumn(name="parent_id", referencedColumnName="id") **/ private $parent; // ... }
Tables • Category