2
votes

I've two entities which has OneToMany mapping just the way described in doctrine docs:

 // Product Entity
 /**
  * @OneToMany(targetEntity="Feature", mappedBy="product")
  */
  private $features;

 // Feature Entity    
 /**
  * @ManyToOne(targetEntity="Product", inversedBy="features")
  * @JoinColumn(name="product_id", referencedColumnName="id")
  */
  private $product;

When I do findAll() on Product then it returns products with array of Feature.

I'm using DQL to query and so I want to know how do I select array of Feature using DQL.

I did: SELECT p.name, p.price, f FROM Product p JOIN p.features f

but it gives an error

Cannot select entity through identification variables without choosing at least one root entity alias.

I also tried: SELECT p.name, p.price, p.features FROM Product p

which also gives an error

Invalid PathExpression. Must be a StateFieldPathExpression.

2
Can you please ost your PHP code also? The DQL does not look wrong by itself, but maybe how you are calling it is the issue. - romaricdrigon

2 Answers

1
votes

The problem is that you can't get the Features entities without getting a Product for contain it. So you must do

SELECT p , f FROM Product p JOIN p.features f

Hope this help you.

0
votes

@abdiel gives right solution

class ProductsRepository extends \Doctrine\ORM\EntityRepository
{

    public function getAllProductsWithFeatures()
    {
        $dql = 'SELECT p , f FROM Product p JOIN p.features f';
        $query = $this->getEntityManager()->createQuery($dql);
        return $query->getResult();
    }

}

Then for example in controller:

$products = $this->get('doctrine')->getRepository('YourBundle:Product')->getAllProductsWithFeatures();

All products will be with preloaded collections of features.

Good luck!