Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 优化有说服力的关系查询_Laravel_Eloquent_Model - Fatal编程技术网

Laravel 优化有说服力的关系查询

Laravel 优化有说服力的关系查询,laravel,eloquent,model,Laravel,Eloquent,Model,我们正在优化搜索页面上的Laravel雄辩查询,我们已经将执行的查询数量降到了一个很好的数字 但是,我们确实看到一个基于关系运行的一致性查询。这个问题是: select * from `property_types` where `property_types`.`id` = 7 limit 1 如果每个属性具有唯一的属性类型,则此查询正在运行 我已经在Laravel中查看了has和查询 关系设置为: public function type() { return $this->

我们正在优化搜索页面上的Laravel雄辩查询,我们已经将执行的查询数量降到了一个很好的数字

但是,我们确实看到一个基于关系运行的一致性查询。这个问题是:

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';
}
因此,每次找到匹配的属性时,它都会返回到该关系,我们会看到属性类型查询每页最多运行15次


有什么优化建议吗?

您尝试过吗?就在您进行选择时,添加一个简单的->with(“关系名称”),它将预加载关系,如@acvi所说,您最好检查并使用渴望加载:。它将减少查询并解决N+1问题