在 Laravel 中,我有一個博客表。我在該表中有類別。我正在尋找每個類別的最新博客;作為結果集。
例子
| ID | 類別ID | 博客標題 | created_at |
|---|---|---|---|
| 1 | 1 | 標題 | 2022-01-01 |
| 2 | 2 | 標題b | 2022-01-02 |
| 3 | 3 | 標題c | 2022-01-03 |
| 4 | 1 | 標題d | 2022-01-04 |
| 5 | 2 | 標題e | 2022-01-05 |
| 6 | 3 | 標題 f | 2022-01-06 |
對于上述情況,我想回傳 id 為 4、5 和 6 的行,因為這將是表created_at中每個的最新category_id行。
我試過了groupBy,但這不起作用。但是,我覺得這應該很容易。所以下面是我最近的嘗試。
blogs = Blogs::where('user_id', $this->id)
->groupBy('category_id')
->orderBy('created_at','desc')
->get();
uj5u.com熱心網友回復:
如果您使用的是 laravel 8 或更高版本,您可以在Category模型上寫下以下關系:
/**
* Get the category's most recent blogs.
*/
public function latestBlogs()
{
return $this->hasMany(Blog::class)->latest();
}
比,當您需要獲取最新博客的所有類別時,您可以呼叫:
Category::query()
->with('lastestBlogs')
->get();
當您需要根據類別獲取所有最新的博客時,您可以呼叫:
Category::query()
->with('lastestBlogs')
->get()
->pluck('lastestBlogs')
->flatten();
uj5u.com熱心網友回復:
您可以嘗試使用這樣的資料庫原始查詢:
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/430342.html
