1

If I have a one-to-many/many-to-one relationship between shop entity and product entity. and I use $products = $shop->getProducts()->toArray(); then dump($products); the products are retrieved by the ascending order of Ids (primary key) and this is the behaviour that I want. I just want to know if that will always be the case because I always want the products to be retrieved in this order : from smallest to biggest ID and I want to know if getProducts() always returns the array this way or I should create a Repo function. I checked the query that is executed and it doesn't have any orderBy attribute so is sort by Id ASC the default one?

Mira chalak
  • 307
  • 3
  • 12
  • 1
    Does this answer your question? [How to OrderBy on OneToMany/ManyToOne](https://stackoverflow.com/questions/12478583/how-to-orderby-on-onetomany-manytoone) – LBA Sep 20 '22 at 07:29
  • 1
    You should consider the records in the database as a "set" (from set theory), having no default order. If no `ORDER BY` clause is specified, the database will return them in some order, but there's no guarantees as to what that order will be or if it's always the same. If you want to make sure your records are always ordered as you would expect, add an `ORDER BY` clause. See also: https://dba.stackexchange.com/a/6053 – Marleen Sep 20 '22 at 07:47
  • 1
    @Marleen Thank you so much for this detailled answer as usual – Mira chalak Sep 20 '22 at 08:26
  • @Marleen if I wanna replace getProducts function by a repo function what will it be ? i wanna the products entities to be loaded just as when i use getProducts function – Mira chalak Sep 20 '22 at 08:27
  • `createQueryBuilder('product')->where('product.shop' := currentShop)->orderBy("product.id", "asc");` then setparameter $shop for the currentShop ? am i missing something – Mira chalak Sep 20 '22 at 08:30
  • honesly i don't wanna add `@ORM\OrderBy({"some_attribute" = "ASC"}` , i either wanna add a repo function or can i just call `$shop->getProducts()->toArray();` then sort this array ? – Mira chalak Sep 20 '22 at 08:34
  • and if I add `@ORM\OrderBy({"some_attribute" = "ASC"}` should i make a migration ? – Mira chalak Sep 20 '22 at 09:22
  • i'm considering using `@ORM\OrderBy({"id" = "ASC"}` – Mira chalak Sep 20 '22 at 09:28
  • 1
    I would go with the annotation, as that's the easiest solution. You shouldn't have to make a migration, since this doesn't change the database structure. – Marleen Sep 20 '22 at 12:01
  • your comments are very very helpful as always @Marleen – Mira chalak Sep 20 '22 at 12:09

0 Answers0