SensacionRC
SensacionRC

Reputation: 615

Symfony 3.4 entity property with array of items from another entity

I have two entities:

ENTITY 1 - BRAND:

<?php
namespace ...;
//Here the use definitions

class Brand
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    //More properties, getters and setters
}
?>

ENTITY 2 - PRODUCT:

<?php
namespace ...;
//Here the use definitions

class Product
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Brand")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="brand_id", referencedColumnName="id")
     * })
     */
    private $brand;

    //More properties, getters and setters
}
?>

I know that I can get the products of a brand consulting PRODUCT directly, thanks to ORM. But is there a way to get all the products consulting over BRAND entity?

I mean, is there a way that adding a property into BRAND entity, something like this:

/**
 * @ORM\ManyToOne(targetEntity="Producto")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="id", referencedColumnName="brand_id")
 * })
 */
private $listOfProducts;

Can I get a list of products?

Upvotes: 0

Views: 620

Answers (1)

Chbig
Chbig

Reputation: 75

Yes you can. On your Brand entity, add OneToMany column like this :

<?php
namespace ...;
//Here the use definitions

class Brand
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Product", mappedBy="brand")
     */
    private $products;

    //More properties, getters and setters
}
?>

Upvotes: 1

Related Questions