当总行数<n

时间:2018-07-22 18:27:52

标签: mysql laravel eloquent

我有一张桌子说菜单。其中只有5条记录,但我需要5条以上的记录,包括重复项。

实际情况下,一群人可以订购同一菜单,例如,如果我有

1)tea

   ->foo

   ->bar

2)coffee

   ->latte

   ->expresso

3)shake

两个或两个以上的人可以点咖啡。

我试图这样做

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

菜单 标签
菜单1 鸡肉
菜单2 vegen
菜单3 鸡肉

您会看到我有两种鸡,如果我想随机取出四只鸡,包括重复鸡,我该怎么办?请指教。

1 个答案:

答案 0 :(得分: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