How to select randomly with doctrine

前端 未结 13 1023
耶瑟儿~
耶瑟儿~ 2020-11-27 20:21

Here is how I query my database for some words

$query = $qb->select(\'w\')
    ->from(\'DbEntities\\Entity\\Word\', \'w\')
    ->where(\'w.indiction         


        
13条回答
  •  爱一瞬间的悲伤
    2020-11-27 20:52

    The Doctrine team is not willing to implement this feature.

    There are several solutions to your problem, each having its own drawbacks:

    • Add a custom numeric function: see this DQL RAND() function
      (might be slow if you have lots of matching rows)
    • Use a native query
      (I personally try to avoid this solution, which I found hard to maintain)
    • Issue a raw SQL query first to get some IDs randomly, then use the DQL WHERE x.id IN(?) to load the associated objects, by passing the array of IDs as a parameter.
      This solution involves two separate queries, but might give better performance than the first solution (other raw SQL techniques than ORDER BY RAND() exist, I won't detail them here, you'll find some good resources on this website).

提交回复
热议问题