I'm new to Symfony and these questions were brought about in the recent course of learning.
Take a store as an example, I'll create two entities, Product and Category, which have a bidirectional Many-to-One relationship.
class Product
{
private $id;
private $name;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="products")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id", nullable=false)
*/
private $category;
}
class Category
{
private $id;
private $name;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category")
*/
private $products;
}
So my 1st question is:
If I want to get all the products in a particular category, should the URL be
/categories?categoryId=1&limit=20&orderBy=name (I know it's a bit silly, but should a Category record contains all the Product information?)
or
/products?categoryId=1&limit=20&orderBy=name
For the latter one, here comes the 2nd question:
I injected the ProductRepository to the ProductController
class ProductController extends Controller
{
private $productRepository;
public function __construct(ProductRepository $productRepository)
{
$this->productRepository = $productRepository;
}
...
}
In order to get all the product in a category, I wrote a method like this:
public function findByCategory(Category $category): array
{
return $this->createQueryBuilder('p')
->andWhere('p.category = :category')
->setParameter('category', $category)
->orderBy('p.name', 'ASC')
->setMaxResults(20)
->getQuery()
->getResult()
;
}
So, in the ProductController, how should I get the Category object from the query string 'categoryId' in the URL? Should I inject CategoryRepository as well or should I simply inject an entity manager object?