Symfony Database Cookbook
Creating classes with Doctrine[edit]
A command line shortcut for the process of creating an entity class described in Generating Database Tables and/or Schema:
$ php app/console doctrine:generate:entity --entity="AppBundle:Category" --fields="name:string(100)"
Specifying foreign keys between tables[edit]
First create a property within the category/group/type class that will hold the records linked to it.[1]
// src/AppBundle/Entity/Category.php
// ...
use Doctrine\Common\Collections\ArrayCollection;
class Category
{
// ...
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
}
Then add a property in the other class to reference the category/group/type class:
// src/AppBundle/Entity/Product.php
// ...
class Product
{
// ...
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
}
Have Doctrine generate getter and setter methods:
$ php app/console doctrine:generate:entities Acme
Examples[edit]
- Tutorials database:
TutorialandTutorialGroupclasses.
Selectively retrieving object properties[edit]
By default Doctrine retrieves all the properties for an object.[2]
$qb = $em->createQueryBuilder();
// You can select multiple properties in the partial statement
$qb
->select('partial Article.{id,title,summary}')
->from('Entity\Article')
;
Controlling the order of associated entities[edit]
With a one-to-many relationship, display the groups, with the associated entities under each group.
In the group entity add an OrderBy annotation to the associated property:
/**
* @var Array List of tutorials in this group.
* @ORM\OneToMany(targetEntity="Tutorial", mappedBy="group")
* @ORM\OrderBy({"slot" = "ASC", "date" = "DESC"})
*/
public $tutorials;
See also[edit]
- DQL User-Defined Functions (wiki)
- Mastering Symfony2 Performance (Octivi.com)
Notes[edit]
- ↑ Relationships/Accosciations, Doctrine documentation, Symfony documentation, "The Book"
- ↑ Some Doctrine 2 Best Practices, UVD
#4 By default Doctrine will fetch all of the properties for a given entity