duanchi0883649 2017-11-01 04:07
浏览 464
已采纳

Laravel中的Eloquent查询速度很慢

I'm doing an application in Laravel 5.3.19, the thing is, I'm doing a query with Eloquent but it is SO slow, I read some forums and seems like I'm doing something wrong, I tried doing this query in the console with the command php artisan tinker and the query work perfectly, the problem is when I log into the URL that I created in the routes/web.php from my browser, the page just load indefinitely and sometimes It gives to me a timeout error. Someone knows what could be the problem?

here are my files:

  • routes/web.php

Route::get('/area_products/listProductsByArea/{area}','AreaProductController@orderProductsListByArea');    
  • Http/controllers/AreaProductController.php (Controller)
public function orderProductsListByArea($area){
    $array_products = [];
    $products = AreaProduct::where('area_id', $area)->get();
    foreach ($products as $data) {
        $product = [
            'id' => $data->id,
            'price' => $data->price,
            'product_id' => $data->product->id,
            'product_name' => $data->product->name,
            'product_category' => $data->product->category->name,
            'product_reference' => $data->product->reference,
            'product_code' => $data->product->code,
            'area_id' => $data->area_id
        ];
        array_push($array_products, $product);
    }
}    
  • Http/AreaProduct.php (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class AreaProduct extends Model{
    public $table = "products_area";
    public function product(){
        return $this->belongsTo('App\Product');
    }
    public function area(){
        return $this->belongsTo('App\Area');
    }
}

Note: This query should return near to 700 results, I noticed the problem is produced when I'm doing the relations stuff like 'product_name' => $data->product->name. Am I doing something wrong?

Thanks for your help.

  • 写回答

1条回答 默认 最新

  • doubei2231 2017-11-01 04:45
    关注

    Since you're using Eloquent relationships can't you just do this:

    public function orderProductsListByArea($area){
        // Load the Area products with the 'product' relationship (eager loading)
        $products = AreaProduct::where('area_id', $area)
            ->with('product')
            ->get();
    
        // Return the list of products
        return $products;
    }
    

    Without seeing the rest of your data/db, I'm pretty sure that should return what you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP