gpt4 book ai didi

symfony - 以随机顺序和限制从数据库中返回随机数据

转载 作者:行者123 更新时间:2023-12-04 13:28:06 25 4
gpt4 key购买 nike

我是 symfony 的新手,我正在尝试以随机顺序查看其中一个表中的数据,限制为 4。我尝试在存储库中执行此操作,但是 RAND()不工作,所以我在 Controller 中尝试。
错误如下:
“警告:array_rand() 期望参数 1 是数组,给定的对象”
我不明白为什么,当在 $response 中时我将数据设置为数组。
这是我的实际代码:

/**
* @Route("/ws/random/superviviente", name="ws_random_survi")
*/
public function randomSurvi(Request $request): Response
{
$data = $request->request->all();
$entityManager = $this->getDoctrine()->getManager();

$randomPerks = $entityManager->getRepository(Perks::class)
->getRandomPerks();

$response = new JsonResponse();
$response -> setStatusCode(200);
$response -> setData(array('random perk' => $randomPerks));

$resultRandom = array_rand($response);

return $resultRandom;

}

最佳答案

您正在尝试在学说数组集合上使用 array_rand。
您可以将其转换为数组并返回到学说数组:

use Doctrine\Common\Collections\ArrayCollection;
public function randomSurvi(Request $request): Response
{
$data = $request->request->all();
$entityManager = $this->getDoctrine()->getManager();

$randomPerks = $entityManager->getRepository(Perks::class)
->getRandomPerks();

$resultRandom = new ArrayCollection(array_rand($randomPerks->toArray()));

return new JsonResponse($resultRandom);

}
否则它将与 shuffle 一起使用:
 $randomPerks = $entityManager->getRepository(Perks::class)->getRandomPerks();
$randomPerks = shuffle($randomPerks);
或直接通过 your method in your repository 获得随机福利.
查看来自 @Krzysztof Trzos 的示例:
  public function getRandomProducts($amount = 7)
{
return $this->getRandomProductsNativeQuery($amount)->getResult();
}


/**
* @param int $amount
* @return ORM\NativeQuery
*/
public function getRandomProductsNativeQuery($amount = 7)
{
# set entity name
$table = $this->getClassMetadata()
->getTableName();

# create rsm object
$rsm = new ORM\Query\ResultSetMapping();
$rsm->addEntityResult($this->getEntityName(), 'p');
$rsm->addFieldResult('p', 'id', 'id');

# make query
return $this->getEntityManager()->createNativeQuery("
SELECT p.id FROM {$table} p ORDER BY RAND() LIMIT 0, {$amount}
", $rsm);
}

关于symfony - 以随机顺序和限制从数据库中返回随机数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66869750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com