How to fetch data from another entity using Doctrine 2

Asked

Viewed 509 times

1

I have two entities a Product (id, id_category, name) and another Category (id, name), in the product entity I want to bring the category name by the product table id_category. There is a way to do this with annotations?

  • Are you mapping classes to tables using the ORM? For example, a Product class corresponds to the Product table, just as a Category class would correspond to the Category table?.

  • Yes, it’s a Many-to-one association. You have an example here: http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html It is in English, but the example is self-explanatory.

1 answer

0


After rereading 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 notes. The relationship can be done in several different ways, being one-way (the relationship information is in only one of the entities) or two-way (the relationship information is in both entities). I personally prefer the latter, which is the one 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 because that way I don’t need to create custom queries in DQL. After generating the stubs (the methods of the above classes), it is possible to search the category of a product with $produto->getCategoria(), in the same way that you search for products from a category with $categoria->getProdutos().

  • Despite the attribute $categoria entail in the creation of the column categoria_id in the product table, the same will not happen because you declared the attribute $produtos in the category table; it is only a relationship information.

  • In the example above, the column categoria_id of Produto will be null as it is standard Doctrine. For the column to be non-null, just add the annotation @ORM\JoinColumn(nullable=false) in the attribute $categoria.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.