如何在Eloquent中使用基于ORDER BY子句的LIMIT查询

时间:2015-06-06 13:44:30

标签: php postgresql laravel eloquent laravel-5

我有两个表(和相应的模型)如下:

TreeSet

posts (
    id            auto_increment,
    category_id   refrences_id_on_categories,
    data          json
    date          timestamp
)

我可以使用以下方式获得5个帖子:

categories (
    id            auto_increment,
    name          text
)

但是,有没有办法使用Post::orderBy('category_id', 'asc')->take(5)->get(); (Laravel 5,dbms:postgres)获得每个Category的5个帖子?

修改我正在寻找单行解决方案,例如使用Eloquent或其他条款。

3 个答案:

答案 0 :(得分:1)

您可以使用Eager Loading来减少查询:

$categories = Category::with('posts')->get();

foreach ($categories as $category)
{
    $posts = $category->posts()->take(5)->get();
}

答案 1 :(得分:0)

如果您在CategoryPost型号之间设置了one-to-many关系,则可以使用该关系以这种方式获得每个类别的5个帖子:

$categories = Category::all();

foreach ($categories as $category)
{
    $posts = $category->posts()->take(5)->get();
}

Category模型中的关系如下所示:

class Category extends Model {

    public function posts()
    {
        return $this->hasMany('App\Post');
    }

}

答案 2 :(得分:0)

根据this answer,我使用DB::select()使用原始查询,如下所示:

$sql = "SELECT * FROM (
  SELECT
    ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY date DESC) AS r,
    t.*
  FROM
    posts t) x full outer join categories t2
  on x.category_id = t2.id
WHERE
  x.r <= 5";

DB::select($sql);