- 在后台中创建分类
在后台中,创建具有排序层数和名称的分类(例如:“主分类”和“子分类”)。
- 将字段添加到模型中
在要排序的模型中,添加一个额外的“sort_order”字段。可以使用以下命令:
php artisan make:migration add_sort_order_to_products_table --table=products
“add_sort_order_to_products_table”可以替换为您的模型名称,例如“add_sort_order_to_pages_table”。
在迁移中添加以下代码:
public function up()
{
Schema::table('products', function($table) {
$table->integer('sort_order')->nullable()->default(0);
});
}
public function down()
{
Schema::table('products', function($table) {
$table->dropColumn('sort_order');
});
}
这将在“products”表中添加一个名为“sort_order”的整数字段。
- 更新控制器
更新要排序的模型的控制器。需要使用以下代码:
use Winter\Storm\Database\Traits\Sortable;
class Product extends Model
{
use Sortable;
public $implement = ['Winter\Storm\Database\Traits\Purgeable'];
public $purgeable = ['_token', 'session_key', 'reorder'];
public function getSortColumn()
{
return 'sort_order';
}
public function scopeIsPublished($query)
{
return $query->where('published', 1);
}
}
在这个示例中,“Product”模型使用了“Sortable”特性。 getSortColumn()方法确定了这个排序应该使用哪个列。这个列使用的名字应该与上一步中新添加的字段相同。
- 更新排序视图
最后,需要在扩展后台排序页面中更新视图。可以使用以下框架:
[{
"columnName": "sort_order",
"title": "Sort",
"order": "asc",
"type": "number",
"width": "20%"
},
{
"columnName": "name",
"title": "Name",
"order": "asc",
"type": "string",
"width": "80%"
}]
这确定了表格中的排序。第一列使用的列名称应该与上一步中新添加的字段相同。