Symfony2 Doctrine get random product from a category

后端 未结 2 2166
生来不讨喜
生来不讨喜 2021-02-10 00:56

I have the following database scheme:

table \'products\'
id
category_id

and of course a category table, just with an id.

The data look

相关标签:
2条回答
  • 2021-02-10 01:51

    Use this helper function:

    <?php
    use Doctrine\ORM\EntityManager;
    
    /**
     * Retrieve one random item of given class from ORM repository.
     * 
     * @param EntityManager $em    The Entity Manager instance to use
     * @param string        $class The class name to retrieve items from
     * @return object
     */ 
    function getRandomDoctrineItem(EntityManager $em, $class)
    {
        static $counters = [];
        if (!isset($counters[$class])) {
            $this->counters[$class] = (int) $this->manager->createQuery(
                'SELECT COUNT(c) FROM '. $class .' c'
            )->getSingleScalarResult();
        }
        return $em
            ->createQuery('SELECT c FROM ' . $class .' c ORDER BY c.id ASC')
            ->setMaxResults(1)
            ->setFirstResult(mt_rand(0, $counters[$class] - 1))
            ->getSingleResult()
        ;
    }
    

    Example usage:

    $randomItem = getRandomDoctrineItem($em, 'Application\Entity\Post');
    
    0 讨论(0)
  • 2021-02-10 01:57

    You first have to count the total number of products, then generate a random offset to select a random product.

    This should get you started:

    $count = $this->createQueryBuilder('u')
                 ->select('COUNT(u)')
                 ->getQuery()
                 ->getSingleScalarResult();
    

    And then you can generate a random number between your 1 and the total number of rows.

    return $this->createQueryBuilder('u')
        ->where('u.category = :category')
        ->setFirstResult(rand(0, $count - 1))
        ->setMaxResults(1)
        ->setParameter('category', $category->getId())
        ->getQuery()
        ->getSingleResult()
    ;
    

    Which translates to:

    SELECT * FROM products WHERE category_id = ? LIMIT 1, {random offset}
    
    0 讨论(0)
提交回复
热议问题