Laravel5.4入门系列10.文章归档
时间:2023-03-29 17:17:20
PHP
首先实现文章按日期统计,原SQL如下:selectyear(created_at)year,monthname(created_at)month,count(*)publishedfrompostgroupbyyear,monthorderbymin(created_at)desc;将其转换为Eloquent模型:/app/Http/Controllers/PostsController.php使用App\Post;publicfunctionindex(){$archives=Post::selectRaw('year(created_at)year,monthname(created_at)month,count(*)published')->groupBy('year','month')->orderByRaw('min(created_at)desc')->get();$posts=Post::latest()->get();returnview('posts.index',compact('posts','archives'));}在视图中显示对应的文章存档:/resources/views/layouts/siderbar.blade.php档案
@foreach($archivesas$archive)month}}&&year={{$archive->year}}">{{$archive->month}} {{$archive->year}}@endforeach
当用户点击某个月份时,传递月份和年份参数到后台,所以index方法也需要根据参数类型选择:/app/Http/Controllers/PostsController.phpuseCarbon\Carbon;publicfunctionindex(){$archives=Post::selectRaw('year(created_at)year,monthname(created_at)month,count(*)published')->groupBy('year','month')->orderByRaw('min(created_at)desc')->get();$posts=Post::latest();如果($month=request('month')){$posts->whereMonth('created_at',Carbon::parse($month)->month);}if($year=request('year')){$posts->whereYear('created_at',$year);$posts=$posts->get();returnview('posts.index',compact('posts','archives'));}这里使用了Laravel提供的whereDate系列方法,用Carbon转换月份封装以上一系列查询:/app/Http/Controllers/PostsController.phppublicfunctionindex(){$archives=Post::archives();$posts=Post::latest()->filter(request(['year','month']))->get();returnview('posts.index',compact('posts','archives'));}模型:/app/Post.phpuseCarbon\Carbon;publicfunctionscopeFilter($query,$value){if($month=$value['month']){$query->whereMonth('created_at',Carbon::parse($month)->month);}if($year=$value['year']){$query->whereYear('created_at',$year);}}publicstaticfunctionarchives(){returnstatic::selectRaw('year(created_at)year,monthname(created_at)month,count(*)published')->groupBy('year','month')->orderByRaw('min(created_at)desc')->get();}至此,我们基本实现了文章归档的功能。但是有一个问题,文章存档实际上是包含在通用视图中的,这意味着所有对网站的请求都需要返回$archives,否则会报错。一种做法是在不同的方法中调用archives()方法返回数据。当然,更简单的方法是使用“查看共享数据”功能。操作如下:/app/Providers/AppServiceProvider.phppublicfunctionboot(){Schema::defaultStringLength(191);view()->composer('layouts.siderbar',function($view){$view->with('archives',\App\Post::archives());});}这个服务提供者包含两个方法:register(),这个是用来绑定IOC容器的(先忽略),绑定之后我们就可以在boot.h中定义我们想要实现的功能了。在此示例中,我们注册了layouts.siderbar视图并将其传递给viewarchives变量。Laravel数据库:数据库请求生成器|Laravel5.4中文文档Carbon-DateTime.Laravel的视图函数的简单PHPAPI扩展|Laravel5.4中文文档