2

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.

1
  • 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. Commented Jul 12, 2016 at 8:09

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

@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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.