【问题标题】:Laravel - Shared data reduce number of queriesLaravel - 共享数据减少查询次数
【发布时间】:2021-09-02 19:40:02
【问题描述】:

我正在尝试在我的网站上创建全局搜索功能,为此我需要查询数据库以获取记录。我的应用程序的前端需要以下数组:

[
 ['name' => 'Result #1...', 'url' => 'http://...'],
 ['name' => 'Result #2...', 'url' => 'http://...'],
 ['name' => 'Result #3...', 'url' => 'http://...'],
]

为此,我在AppServiceProvider 中添加了以下内容:

public function boot()
{
    view()->composer('*', function($view) use ($auth) {
            return \View::share('SearchData', (new GlobalSearch($auth->user()->currentTeam))->all());
    });
}

$SearchData 是在 GlobalSearch 类中创建的:

class GlobalSearch
{
    public $data;

    public function __construct(public Team $team){
        $this->data = $team->properties()->with(['leases', 'leases.tenant', 'leases.files', 'leases.invoices']);
    }


    protected function propertyData() : array
    {
    
        $properties = $this->data->get();

        return $properties->map(function ($property) {
            $array['name'] = \Str::limit($property->address, 40);
            $array['url'] = route('properties.show', ['property' => $property]);
            
            return $array;
        })->toArray();    


    }


    public function all() : array
    {
       return $this->propertyData();
    }
}

现在上面的代码可以工作了——我成功地在正确的映射中得到了一个数组。但是,在我的数据库中,properties 表中只有 1 属性 - 然而,对于单个页面加载,执行了 90 个重复查询。

为什么会这样?我似乎无法找到这些查询重复的原因

【问题讨论】:

    标签: php laravel laravel-8


    【解决方案1】:

    您实际上可以删除 view()->composer('*', function) 部分。由于View::share() 的作用完全相同。

    $searchData = (new GlobalSearch($auth->user()->currentTeam))->all();
    View::share('SearchData', $searchData);
    

    可选:

    您可以将GlobalSearch 类绑定到AppServiceProvider 中的容器。这将使课程可以通过app(GlobalSearch::class) 在应用程序中的任何位置使用。这意味着查询只会在初始化过程中运行一次并维护数据。

    有关单例绑定的更多信息:https://laravel.com/docs/8.x/container#binding-a-singleton

    $this->app->singleton(GlobalSearch::class, function ($app) {
        return new GlobalSearch(auth()->user()->team);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2017-04-20
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多