编程

Laravel 11 开始支持立即加载限制

858 2024-02-07 04:33:00

随着 Laravel 11 于 2024 年 2 月发布,Laravel 将原生支持对每个父级立即加载的结果数量进行限制。

We've integrated the code behind @staudenmeir's "eager load limit" package into Laravel 11.

That means in Laravel 11 this will actually work... retrieving users while eager loading only 5 posts per user... ❤️

Thanks @staudenmeir! pic.twitter.com/4IAbefwVJP

— Taylor Otwell (@taylorotwell) January 16, 2024

比如,你希望分页显示用户,同时立即加载每个用户的最新三篇文章:

User::with([
    'posts' => fn ($query) => $query->limit(3)
])->paginate();

上述 Eloquent 查询使用优化过的立即加载模型,就像下面开箱即用展示的 JSON:

使用 Laravel 10 或者以下版本,仍然可以通过 Jonas Staudenmeir 的 eager-load-limit 包使用该功能,不过 Laravel 11 现在开箱即用原生支持该功能。以下是 Laravel 11  对上述代码进行查询的示例:

select count(*) as aggregate from `users`
select * from `users` limit 15 offset 0
select * from (
  select *, row_number() over (partition by `posts`.`user_id`)
  as `laravel_row` from `posts`
  where `posts`.`user_id` in (1, 2, 3...)
)
as `laravel_table` where `laravel_row` <= 3
order by `laravel_row`