【发布时间】: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 个重复查询。
为什么会这样?我似乎无法找到这些查询重复的原因
【问题讨论】: