How to select randomly with doctrine

前端 未结 13 1015
耶瑟儿~
耶瑟儿~ 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:26

    For me, the most useful way was to create two arrays where i say order type and different properties of the Entity. For example:

        $order = array_rand(array(
            'DESC' => 'DESC',
            'ASC' => 'ASC'
        ));
    
        $column = array_rand(array(
            'w.id' => 'w.id',
            'w.date' => 'w.date',
            'w.name' => 'w.name'
        ));
    

    You could add more entries to array $column like criteria.

    Afterwards, you can build your query with Doctrine adding $column and $order inside ->orderBy. For example:

    $query = $qb->select('w')
    ->from('DbEntities\Entity\Word', 'w')
    ->where('w.indictionary = 0 AND w.frequency > 3')
    ->orderBy($column, $order)
    ->getQuery()
    ->setMaxResults(100);
    

    This way improved the performance of my application. I hope this helps someone.

提交回复
热议问题