gpt4 book ai didi

php - 多个重复查询 - Laravel

转载 作者:行者123 更新时间:2023-11-29 11:00:21 25 4
gpt4 key购买 nike

我首先展示在我的 Controller 中编写的代码:

public function __construct(Utility $utility)
{
$league = $utility->checkDomainController();
view()->share('league', $league);
$this->league = $league;
}

public function getDashboard()
{
return view('dashboard.dashboard', compact('activities'));
}

现在我想在 Controller 中存在的方法的所有 View 中共享$league。 ( $league 仅包含一个查询)。

但现在我面临的问题是,查询与包含的 View 主视图的数量重复。这里仪表板是主视图。因此,现在如果主视图中包含 7 个 View ,则 $league 上的查询将执行 7 次。以下是图片:

dashboard.blade.php 中包含的 View 图片 Picture of views included in dashboard.blade.php

查询被重复的图片 Picture of Queries getting duplicated

有什么解决办法吗?有更好的方法来处理这个问题吗?

最佳答案

一些解决方案向您开放。

一种解决方案是缓存查询。仅当您的 $league 数据不经常更改时才有效。

$league = Cache::remember('users', $minutes, function () {
return $utility->checkDomainController();
});

另一个解决方案是使用 View Composer。仅当呈现该特定 View 时才会调用它。因此,如果您包含一次,它就会渲染一次。

View::composer('leagues', function ($view) {
//
});

在此处了解有关 View 编辑器的更多信息:https://laravel.com/docs/5.4/views#view-composers

关于php - 多个重复查询 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42393919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com