简体   繁体   English

多个重复查询-Laravel

[英]Multiple Duplicated Queries - Laravel

I'm first showing the code written in my 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'));
}

Now I want to share $league in all the views in the methods present there in the controller. 现在,我想在控制器中存在的方法的所有视图中共享$ league ( $league consists of one query only ). ($ league仅包含一个查询)。

But now what problem I'm facing is, query gets duplicated with the number Included Views with the Main View . 但是现在我面临的问题是,查询被重复,并且Main View 包含了Included Views Here dashboard is the main view. 这里的仪表板是主视图。 So now if 7 views are included in Main View then query on $league gets executed 7 times. 因此,现在如果在主视图中包含7个视图,则对$ league的查询将被执行7次。 Below are the pictures: 以下是图片:

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

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

Any solution to this? 有什么解决办法吗? Any better way to handle this? 还有更好的方法来解决这个问题吗?

A few solutions open to you. 一些解决方案向您开放。

One solution would be to cache the query. 一种解决方案是缓存查询。 Only efficient if your $league data does not frequently change. 仅在您的$league数据不经常更改时才有效。

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

Another solution would be to use View Composer. 另一个解决方案是使用View Composer。 It will be called only when that specific view is rendered. 仅在渲染该特定视图时才会调用它。 So if you include it once, it renders once. 因此,如果将其包含一次,它将呈现一次。

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

Read more about view composers here: https://laravel.com/docs/5.4/views#view-composers 在此处阅读有关视图作曲家的更多信息: https : //laravel.com/docs/5.4/views#view-composers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM