$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());
});
$model中没有预加载关联模型,这里出现了n+1问题
这个问题无解,就算设置了预加载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问题.
Most helpful comment
不知这个方法可不可行 可以先把关联表的数据预加载进来
这样就可以避免使用get()而导致N+1问题.