优化雄辩的关系查询

时间:2020-10-30 08:26:15

标签: laravel eloquent model

我们正在搜索页面上优化我们的Laravel Eloquent查询,我们已将执行的查询数量降低到一个不错的数量。

但是,我们确实看到了基于关系运行的一致查询。该查询是:

select * from `property_types` where `property_types`.`id` = 7 limit 1

如果每个属性都有唯一的属性类型,则此查询正在运行。

我已经研究过Laravel中的has和查询。

关系已设置:

public function type()
{
    return $this->belongsTo('App\Models\PropertyType', 'property_type_id', 'id');
}

我们使用该关系创建属性标题和URL,因此对于URL,我们使用:

public function getUrlAttribute($pdf = false)
{
    $property_route = ($pdf) ? 'property-pdf' : 'property';

    // Format: /property/[NUMBER OF BEDS]-bed-[PROPERTY TYPE]-[FOR-SALE / TO-RENT]-in-[CITY]/[PROPERTY ID]
    $items = [];
    if ($this->beds) $items[] = $this->beds.' bed';
    $items[] = $this->type->name ?? 'property';
}

因此,每次找到匹配的属性时,它就会重新建立这种关系,并且我们看到property_types查询每页最多运行15次。

是否有优化建议?

0 个答案:

没有答案