Laravel-admin: expand 列展开n+1问题

Created on 18 Mar 2019  ·  4Comments  ·  Source: z-song/laravel-admin

  • Laravel Version: 5.7.*
  • PHP Version:7.2
  • Laravel-admin: 1.6.*

Description:

$grid->model()->load('comments');
$grid->title('标题')->expand(function ($model) {

$comments = $model->comments()->take(10)->get()->map(function ($comment) {
    return $comment->only(['id', 'content', 'created_at']);
});

return new Table(['ID', '内容', '发布时间'], $comments->toArray());

});

Steps To Reproduce:

$model中没有预加载关联模型,这里出现了n+1问题

wontfix

Most helpful comment

不知这个方法可不可行 可以先把关联表的数据预加载进来

$grid->model()->with(['comments']);

$grid->title('Title')->expand(function () {
     $comments = $this->comments->map(function ($comment) {
        return $comment->only(['summary', 'content']);
    });
    return new Table(['Summary', 'Content'], $comments->toArray());
});

这样就可以避免使用get()而导致N+1问题.

All 4 comments

这个问题无解,就算设置了预加载load('comments'), $model->comments()->take(10)还是会去查数据库

预加载应该把关联表的数据加载进来了吧,上面的单个$model应该就有预加载关联表的数据了,而不是再去关联的表中拿出数据,我这样理解的对吗?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

不知这个方法可不可行 可以先把关联表的数据预加载进来

$grid->model()->with(['comments']);

$grid->title('Title')->expand(function () {
     $comments = $this->comments->map(function ($comment) {
        return $comment->only(['summary', 'content']);
    });
    return new Table(['Summary', 'Content'], $comments->toArray());
});

这样就可以避免使用get()而导致N+1问题.

Was this page helpful?
0 / 5 - 0 ratings