当总行数为< n

问题描述 投票:0回答:1

我有一张桌子,上面写着菜单。其中只有 5 条记录可用,但我需要超过 5 条记录,包括重复记录。

实际场景,一群人可以点相同的菜单,例如如果我有

1)tea

   ->foo

   ->bar

2)coffee

   ->latte

   ->expresso

3)shake

两人或多人可以点咖啡。

我尝试这样做

$menu = RestaurantsMenu::where('tag','=','Coffee')
                                ->get()
                                ->random(5);

菜单       标签      
菜单 1      鸡肉      
菜单 2      素食      
菜单 3      鸡肉      

你可以看到我有两种鸡,如果我想随机取出4只鸡,包括重复的鸡,我该怎么做?请指教。

php mysql laravel eloquent
1个回答
0
投票

问题在写作时更新了,我对问题的解释可能不正确 - 现在就保留它

原始解释:如果数据库中的行数少于X行,如何通过随机复制其他行来创建具有X个条目的结果集。


原答案:

这种重复应该在查询完现有数据后仅使用 PHP 来完成。

我会使用一个函数来获取查询和所需的结果数量,然后从现有的行中随机创建足够的行。

function fillResultsWithDuplicates($query, $numRowsNeeded) {
  // avoid querying _more_ than needed when you have sufficient
  $res = $query->random($numRowsNeeded); 

  // may need to coerce into an array - not familiar with laravel
  return fillArrayWithRandomDuplicates($res, $numRowsNeeded);
}  

function fillArrayWithRandomDuplicates($vals, $numEntriesNeeded) {
  /*im sure this can be written to be faster and more succinct
  could accept an optional function to perform the filling*/
  if (count($vals) >= $numEntriesNeeded) return $vals;
  $numDuplicatesNeeded = $numEntriesNeeded - count($vals);
  $dupes = [];

  // Here your are pulling random values from your array to act as duplicates needed
  for ($i = 0; $i < $numDuplicatesNeeded; $i++) {
      $dupes[] = $vals[mt_rand(0, count($vals)-1)]; // array_rand could be used as well but may be slower
  }

  // Maybe shuffle as well if you need
  return array_merge($dupes, $vals);
}

您的情况的用法

$menu = RestaurantsMenu::where('tag','=','Coffee')->get()
$filledMenu = fillResultsWithDuplicates($menu, 5);

使用简单数组的演示:

$initial = ["a", "b", "c"];
$filled = fillArrayWithRandomDuplicates($initial, 10);
// will contain 7 random selections of a,b,c followed by original a,b,c for total 10 entries
// ex: bcaaabaabc - add shuffles as needed
© www.soinside.com 2019 - 2024. All rights reserved.