Symfony2 Doctrine get random product from a category(Symfony2 Doctrine 从一个类别中获取随机产品)
问题描述
我有以下数据库方案:
table 'products'
id
category_id
当然还有一个类别表,只有一个 id.
and of course a category table, just with an id.
数据看起来像这样:
Products
--------------------
| id | category_id |
--------------------
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 2 |
| 5 | 1 |
--------------------
我想选择一个类别(例如类别 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?
我在实体Category"和Product"之间有一个 OneToMany 关系,所以我也可以通过 category->getProducts()...
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
推荐答案
你首先要统计产品的总数,然后生成一个随机偏移量来选择一个随机产品.
You first have to count the total number of products, then generate a random offset to select a random product.
这应该让你开始:
$count = $this->createQueryBuilder('u')
->select('COUNT(u)')
->getQuery()
->getSingleScalarResult();
然后你可以在你的 1 和总行数之间生成一个随机数.
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()
;
翻译为:
SELECT * FROM products WHERE category_id = ? LIMIT 1, {random offset}
这篇关于Symfony2 Doctrine 从一个类别中获取随机产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony2 Doctrine 从一个类别中获取随机产品


基础教程推荐
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01