Laravel 有口才倾向的随机选择记录

Laravel 有口才倾向的随机选择记录,laravel,laravel-5,eloquent,laravel-5.2,Laravel,Laravel 5,Eloquent,Laravel 5.2,我有一个模型Quote,它有两个属性:Quote和probability。我想随机选择一个引号,但概率较高的引号必须更频繁地选择。例如,如果我们有 $q1->probability == 0.15 及 后者必须是被选择可能性的5倍。以下命令进行随机报价选择: $quote = Quote::orderByRaw('RAND()')->first(); 但是我需要选择有偏见的,正如上面提到的。如何实现这一点?我不确定是否有一种方法可以通过MySQL实现这一点,但这个问题以前已经用P

我有一个模型
Quote
,它有两个属性:Quote和probability。我想随机选择一个引号,但概率较高的引号必须更频繁地选择。例如,如果我们有

$q1->probability == 0.15

后者必须是被选择可能性的5倍。以下命令进行随机报价选择:

$quote = Quote::orderByRaw('RAND()')->first();

但是我需要选择有偏见的,正如上面提到的。如何实现这一点?

我不确定是否有一种方法可以通过MySQL实现这一点,但这个问题以前已经用PHP提出并解决过:

基本上,您希望提取引号id和权重(
[id=>1,weight=>0.5]
)以及所有权重的总和(
0.90
)。然后,在没有特定顺序的情况下,在数组中循环并减去每个权重

因此,如果我有一个MySQL表,其中包含这些值

[
    [ 'id' => 1, weight => 1 ],
    [ 'id' => 2, weight => 2 ],
    [ 'id' => 3, weight => 4 ],
]
然后您将生成一个介于
0
7
之间的数字,因为这是所有权重的总和。在这一点上,你把每一项从随机数中减去。一个例子是这样的

$quoteWeights = Quote::select('id', 'weight')->get();
$weightSum    = $quoteWeights->sum('weight');
$weightRand   = mt_rand(0, $weightSum);

foreach ($quoteWeights as $quoteWeight)
{
    // Subtract our weight from the rand.
    $weightRand -= $quoteWeight->weight;

    // If it's bust, we want to return the winning model.
    if ($weightRand <= 0)
    {
        // Refresh the model so we get all attributes.
        return $quoteWeight->fresh();
    }
}
$quoteWeights=Quote::select('id','weight')->get();
$weightSum=$quoteWeights->sum('weight');
$weightRand=mt_rand(0$weightSum);
foreach($quoteWeight作为$quoteWeight)
{
//用兰特减去我们的重量。
$weightRand-=$quoteWeight->weight;
//如果它破产了,我们想退回获胜的模型。
如果($weightRand fresh();
}
}
这是未经测试的代码,但我打赌它会正确运行


如果您有一个高负载服务器或一个巨大的报价数据库,您可能需要在第一部分调用缓存。

谢谢您的回答。技术不错
$quoteWeights = Quote::select('id', 'weight')->get();
$weightSum    = $quoteWeights->sum('weight');
$weightRand   = mt_rand(0, $weightSum);

foreach ($quoteWeights as $quoteWeight)
{
    // Subtract our weight from the rand.
    $weightRand -= $quoteWeight->weight;

    // If it's bust, we want to return the winning model.
    if ($weightRand <= 0)
    {
        // Refresh the model so we get all attributes.
        return $quoteWeight->fresh();
    }
}