Search code examples
objectdoctrine-ormdqlidentifier

Using object vs Identifier in doctrine 2 DQL


So my friend and me were discussing on whether to use object or id in DQL I searched on internet but I couldn't find anything in doctrine documentation to see which is the best practice So the problem is like this Imagine you have the Category object You want to get the products that have the price less than 10 so for better performance you make a DQL in the product repository and pass the $category object My friend says we should pass $category->getId() and search by Id like this

public function findCheapProducts($categoryId){
return $this->createQueryBuilder('p')
            ->where('p.category = :categoryId')
            ->andWhere('p.price < :price')
            ->setParameters(array(
                'categoryId' => $categoryId,
                'price'      => 10
            ));
}

But what I say is like this

public function findCheapProducts(Category $category){
return $this->createQueryBuilder('p')
            ->where('p.category = :categoryId')
            ->andWhere('p.price < :price')
            ->setParameters(array(
                'categoryId' => $category,
                'price'      => 10
            ));
}

I wrote the code here so the error or things doesn't really matter to me here The objective is to see which is the better way to put a condition by the identifier


Solution

  • I'm mixing both depending on the user input. When I already have the object I pass it, if I only have the ID like after a form submission I pass the ID as it would be nonsense to load the model just to pass it to into the querybuilder. (ofc. you need a proper form validation in this case to avoid wrong IDs)