I have two entities a Product (id, category_id, name) and another Category (id, name), in the product entity want to bring the name of the category by the category_id of the product table. Is there a way to do this with annotations?
I have two entities a Product (id, category_id, name) and another Category (id, name), in the product entity want to bring the name of the category by the category_id of the product table. Is there a way to do this with annotations?
After reading the question I saw that it is a Many-To-One association. Come on then: you need to create two classes - Produto
and Categoria
- and map relationships using annotations. The relationship can be made in a number of different ways, either unidirectional (relationship information stays in only one entity) or bidirectional (relationship information stays in both entities). Personally I prefer the latter, which is what I will use to explain your case.
Class Produto
:
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Produto
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="produtos")
*/
protected $categoria;
/**
* @ORM\Column(type="string")
*/
protected $nome;
}
class Categoria
:
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Categoria
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Phone", mappedBy="user")
*/
protected $produtos;
/**
* @ORM\Column(type="string")
*/
protected $nome;
}
Some important points:
I prefer to use bi-directional relationships in almost 100% of cases, so I do not need to create custom queries in DQL. After generating the stubs (methods of the above classes), you can search for the category of a product with $produto->getCategoria()
, in the same way that you search for products in a category with $categoria->getProdutos()
.
Although the $categoria
attribute implies creating the categoria_id
column in the product table, it will not happen because you declared the $produtos
attribute in the category table; it's just a relationship information.
In the example above, the categoria_id
column of Produto
will be null because it is Doctrine default. For the column to be non-null, simply add the annotation @ORM\JoinColumn(nullable=false)
in the $categoria
attribute.