rtablada/eloquent-rankable

一个可排序的 Eloquent 模型包

dev-master 2013-08-02 18:29 UTC

This package is not auto-updated.

Last update: 2024-09-23 14:54:46 UTC


README

此包使可排序模型排序变得快速且简单。

设置可排序模型

创建可排序模型与创建常规 Eloquent 模型一样简单,只需多一个属性 protected $metricsWeight

一个示例模型可能看起来像这样

use Rtablada\EloquentRankable\RankableModel;

class Friend extends RankableModel
{
	protected $metricWeights = array(
		'search' => 0.8,
		'name' => 0.2
	);

	protected $fillable = array('name', 'rank');
}

在您的模式中,请记得包含一个 rank 列(我建议使用具有 10 位数字和 4 位小数的 Decimal 字段类型)。

$metricWeight 属性

$metricWeight 属性是修改模型排名属性的一种简单方法。您可以为使用 updateMetric* 函数时设置权重。

因此,如果您想在搜索结果中获得结果时更新模型的排名,可以运行 $model->updateMetricSearch(),这将使排名提高 0.8 点。

这些 updateMetric 函数也可以用于修改器或访问器。

public function setNameAttribute($value)
{
	$this->attributes['name'] = $value;
	$this->updateMetricName();
}

排名查询

任何您想要按 rank 降序排序的结果时,只需在想要的查询构建函数前加上 rank 即可。例如

$friends = Friend::rankAll();
$friendsPaginated = Friend::rankPaginate();

按与其他条目比较的方式更新排名

模型还为您提供 rankBeforerankBetweenrankAfter 另一个模型实例的能力。

$friendLow = Friend::find(1);
$friendHigh = Friend::find(1);

$friendLow->rankBefore($friendHigh);

按排序的 ids 更新所有条目

对于类似 JavaScript Web 应用程序的使用,Rankable 提供了一种快速简单的方法来更新条目之间的排名。

$desiredIds = array(1,2,3);
$friends = Friend::rankOrderSet($desiredIds);