因此,我想按月对所有帖子进行排序,按月对某种帖子历史进行排序,为此,我想使用我的created_at
模型的Post
字段,如何实现呢? / p>
这是我的帖子迁移:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('body');
$table->string('image')->nullable();
$table->boolean('isVisible')->default(true);
$table->timestamps();
});
这是我的方法控制器,我想在其中收集每个月变量中的所有帖子,不知道我应该执行什么数据库查询才能完成此操作...
public function posts_by_month()
{
$january = Post::;
$february = Post::;
$march = Post::;
return response()->json([
'success' => 'All posts gathered by month',
'january' => $january,
'february' => $february,
'march' => $march,
/* ... */
]);
}
这是jQuery代码,我将结果附加到每个帖子月份容器中:
$.ajax({
async: true,
url: '/posts-by-month',
type: 'GET',
dataType: 'JSON',
success: function(data) {
$(".history[data-link='january']").append(generateHtml(data.january));
$(".history[data-link='february']").append(generateHtml(data.february));
$(".history[data-link='march']").append(generateHtml(data.march));
$(".history[data-link='april']").append(generateHtml(data.april));
/* ... */
},
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
}
});
function generateHtml(data) {
var post_template = '';
$.each(data, function(index, item) {
post_template += '<div style="width:auto; height:auto; display:flex; align-items:center; margin:5px 0px; margin-left:30px;">';
post_template += '<i class="fa fa-circle" style="color:rgba(0,0,0,0.8); font-size:4px; margin-right:5px;"></i>';
post_template += '<a href="" style="font-size:15px; color:rgba(0,0,0,0.7);">' + item.title + '</a>';
post_template += '</div>';
});
return post_template;
}
答案 0 :(得分:0)
您可以将每一行的created_at
值格式化为月份,然后在从数据库中检索日期时,根据需要对月份进行排序。
$posts = Post::selectRaw("title, body, image, isVisible, date_format(created_at, '%M') month")
->get()
->sortBy('month');
现在,在每个帖子的模型中,您都有一个名为month
的字段。
答案 1 :(得分:0)
在集合中使用groupBy:
public function posts_by_month()
{
return Post::all()->groupBy(function($post) { // Get all posts as collection and apply groupBy method
$post->created_at->format('F'); // ex: September
});
// {'September':[{'id':1, ...}, {'id':2, ...}], 'December':[{'id':3, ...}, {'id':4, ...}]}
}