在 Laravel 8 中,我可以提取特定 table 中的行并获取每个类别的最新 ID 吗?

In Laravel 8 can I pull the rows in a specific table and get the latest per category id?

在Laravel,我有一个博客table。我在 table 中有类别。我正在寻找每个类别的最新博客;作为结果集。

例子

id category_id blog_title created_at
1 1 title a 2022-01-01
2 2 title b 2022-01-02
3 3 title c 2022-01-03
4 1 title d 2022-01-04
5 2 title e 2022-01-05
6 3 title f 2022-01-06

对于上述内容,我想要 return 行 ID 为 4、5 和 6,因为这将是 [=31] 中每个 category_id 的最新 created_at =].

我已尝试 groupBy,但这不起作用。但是,我觉得这应该很容易。下面是我最近的尝试。

blogs = Blogs::where('user_id', $this->id)
    ->groupBy('category_id')
    ->orderBy('created_at','desc')
    ->get();

如果您使用的是laravel 8或更高版本,您可以在Category型号上写下以下关系:

/**
 * Get the category's most recent blogs.
 */
public function latestBlogs()
{
    return $this->hasMany(Blog::class)->latest();
}

然后,当您需要获取所有类别的最新博客时,您可以调用:

Category::query()
     ->with('lastestBlogs')
     ->get();

当您需要根据分类获取所有最新的Blogs时,您可以调用:

Category::query()
     ->with('lastestBlogs')
     ->get()
     ->pluck('lastestBlogs')
     ->flatten(); 

您可以尝试使用这样的数据库原始查询:

DB::table('blogs as b')
    ->select('b.*')
    ->leftJoin('blogs as b2', function ($join) {
        $join->on('b.id','=','b2.id')
             ->where('t.created_at', '<', 't1.created_at');
    })
    ->whereNull('b1.id')
    ->get();