Search code examples
phpsymfonyjoinnesteddoctrine

Doctrine join Entity with join OneToMany


I have entity named Sections, who have:

/**
 * @ORM\OneToMany(targetEntity="Product", mappedBy="sections")
 */
protected $products;

And entity named Product, who have:

/**
 * @ORM\OneToMany(targetEntity="Price", mappedBy="product")
 */
protected $price;

Now I use:

    $sectionsarray = $this->getDoctrine()
           ->getRepository('AsortBundle:Sections')
           ->createQueryBuilder('e')
           ->leftJoin('e.products', 'p')
           ->leftJoin('e.colors', 'c')
           ->select('e, p, c')
           ->orderBy('e.sequence', 'asc')
           ->addOrderBy('p.kolejnosc', 'asc')
           ->addOrderBy('c.sequence', 'asc')
           ->getQuery()
           ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

How I can join price of these product? Price is array collection because it have four currencies.


Solution

  • ok I wrote custom getters and for now work nice :)

    in Price Entity:

    /**
     * Get val
     *
     * @return string 
     */
    public function getValWithCurrency()
    {
        return array($this->currency->getIso() => $this->val);
    }
    

    in Product Entity:

    /**
     * Get val
     *
     * @return string 
     */
    public function getPriceArray()
    {
        $arr = array();
        $pra = $this->price->toArray();
        foreach($pra as $k => $v){
            $a = $v->getValWithCurrency();
            $arr = array_merge($arr, $a);
        }
        return $arr;
    }
    

    enter image description here

    I can now add getter with currency from session or use currency session like a key.

    And for get all:

        $c = $this->get('session')->get('currency');
        $sectionsarray = $this->getDoctrine()
               ->getRepository('AsortBundle:Sections')
               ->createQueryBuilder('e')
               ->select('e, p, c, prices, cur')
               ->leftJoin('e.products', 'p')
               ->leftJoin('p.price', 'prices')
               ->leftJoin('e.colors', 'c')
               ->leftJoin('prices.currency', 'cur')
               ->where('cur.iso = :sesscurr')
               ->setParameter('sesscurr', 'PLN')
               ->orderBy('e.sequence', 'asc')
               ->addOrderBy('p.kolejnosc', 'asc')
               ->addOrderBy('c.sequence', 'asc')
               ->getQuery()
               ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
    

    Thanks!