Symfony2 Doctrine get random product from a category

喜夏-厌秋 提交于 2019-12-09 06:31:39

问题


I have the following database scheme:

table 'products'
id
category_id

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

The data look something like that:

Products
--------------------
| id | category_id |
--------------------
| 0  | 1           |
| 1  | 1           |
| 2  | 1           |
| 3  | 2           |
| 4  | 2           |
| 5  | 1           |
--------------------

I would like to select a category(for example Category 1), so I select all the rows from that category in my product-repository class:

return $this
    ->createQueryBuilder('u')
    ->andWhere('u.category = :category')
    ->setMaxResults(1)
    ->setParameter('category', $category->getId())
    ->getQuery()
    ->getSingleResult()
;

How I can select now a random product? Also: Is it possible to solve this via Relationships?

I have a OneToMany Relationship between the entities "Category" and "Product", so I could also get all the products via category->getProducts()...

Any help would be really useful, thanks


回答1:


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}



回答2:


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');


来源:https://stackoverflow.com/questions/16625994/symfony2-doctrine-get-random-product-from-a-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!