Laravel 5~实现速查表
平时我们可能需要做一个速查表,那么速查表的关键在于怎么将每个单词进行排序,按照什么样的规则排序呢?一般情况下,我们都是按照字典顺序,也就是按照首字母来排序,so,我们就来利用Laravel5来实现这样的功能!
1.准备工作
设计一张表tag
,其作用用来显示所有的word
,表结构如下:
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
利用factory
生成相应的数据,这里我们生成200条数据,在生成数据前请确认您的factory
写好了适配的代码:
$factory->define(App\Tag::class, function (Faker\Generator $faker) {
return [
'name' => $faker->unique()->word,
];
});
然后执行:
php artisan tinker
factory(App\Tag::class,200)->create();
至此,已经完成的准备工作
2.逻辑编写
我们现在已经拥有了200个单词了,那么如何利用model
来对着200个单词进行按大写字母来排序呢,那么我们就需要用到数据库中的函数orderBy
和groupBy
函数了,具体的代码如下:
web.php
Route::get('/tag/show', function () {
$tags = \App\Tag::orderBy('name')->get()->groupBy(function ($tag) {
return substr($tag->name, 0, 1);
});
return $tags;
return view('tags.show', compact('tags'));
});
其中groupBy
函数内部的函数返回的是每个单词的首字母,这样一来我们就将200个单词按照每个单词的首字母的顺序进行分组排序了,结果大概如下:
{
"a": [
{
"id": 94,
"name": "a",
"created_at": "2017-08-05 02:56:59",
"updated_at": "2017-08-05 02:56:59"
},
{
"id": 92,
"name": "ab",
"created_at": "2017-08-05 02:56:59",
"updated_at": "2017-08-05 02:56:59"
},
{
"id": 115,
"name": "accusamus",
"created_at": "2017-08-05 02:56:59",
"updated_at": "2017-08-05 02:56:59"
},
],
"b": [
{
"id": 48,
"name": "beatae",
"created_at": "2017-08-05 02:56:59",
"updated_at": "2017-08-05 02:56:59"
},
{
"id": 57,
"name": "blanditiis",
"created_at": "2017-08-05 02:56:59",
"updated_at": "2017-08-05 02:56:59"
}
],
//省略...
}
然后我们利用foreach
进行输出数据:
@foreach($tags as $letter =>$tagCollection)
<div class="letter-group title is-1">
{{$letter}}
</div>
<ul>
@foreach($tagCollection as $tag)
<li class="title is-5">
<a href="{{url('/tags/'.$tag)}}">{{$tag->name}}</a>
</li>
@endforeach
</ul>
@endforeach
3.完整前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.0/css/bulma.min.css">
<link rel="stylesheet" href="{{mix('/css/app.css')}}">
</head>
<body>
<div class="section hero is-primary is-bold">
<div class="hero-body">
<div class="container">
<h1 class="title">Tags</h1>
<p class="subtitle">
Every tag on the title.
</p>
</div>
</div>
</div>
<div class="section">
<div class="container">
<ul class="has-colums">
@foreach($tags as $letter =>$tagCollection)
<div class="letter-group title is-1">
{{$letter}}
</div>
<ul>
@foreach($tagCollection as $tag)
<li class="title is-5">
<a href="{{url('/tags/'.$tag)}}">{{$tag->name}}</a>
</li>
@endforeach
</ul>
@endforeach
</ul>
</div>
</div>
</body>
</html>
效果图
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 7年前 自动加精
推荐文章: