【问题标题】:is that possible to get data once and the perfrorm query on that instead of database in laravel?是否可以一次获取数据并对其执行查询而不是 laravel 中的数据库?
【发布时间】:2021-05-30 11:14:54
【问题描述】:

是否可以一次获取数据,然后对其执行查询而不是数据库。因为我正在为近 500 个客户进行计算。因为虽然我需要为数据库中的每个客户以相同的模式运行近 100 个查询,这就是为什么我问我是否可以一次获取数据然后对该数据而不是数据库执行查询。因为每次为每个客户增加mysql cpu消耗

我现在在做什么

foreach($customers as $customer)
{
 $customer_charge=  CustomerCharge::where('customer_id',$customer->id)->with('rate_charge')->with('chilled_rate_card')-->with('frozen_rate_card')->get()
$this->calculateConsignment($customer_charge);
}

我想这样做

$customer_charge=  CustomerCharge::whereIn('customer_id',[array])->with('rate_charge')->with('chilled_rate_card')-->with('frozen_rate_card')->get()


Now find() here customer charge form $customer_charge object instead of database

如果可以,那可以吗?

这可能吗?

【问题讨论】:

    标签: php mysql laravel laravel-5 eloquent


    【解决方案1】:

    是的

    当你执行查询时,Laravel 会返回一个 Eloquent 集合,它允许你仍然可以调用相同的方法来检索特定数据:

    $customer_ids = $customers->pluck('id'); // Assuming $customers is an Eloquent Collection
    
    $charges =  CustomerCharge::whereIn('customer_id', $customer_ids)
            ->with('rate_charge')
            ->with('chilled_rate_card')
            ->with('frozen_rate_card')
            ->get();
    
    foreach($customers as $customer)
    {
        $customer_charge =  $charges->where('customer_id', $customer->id)->first(); // querying the already retrieved $charges data, not the database
        $this->calculateConsignment($customer_charge);
    }
    

    【讨论】:

    • 希望这个查询不要再去数据库了??
    • 没有。只有检索所有费用的查询才会进入数据库。在循环中,您查询的是已经检索到的 $charges 数据,而不是数据库。
    • 非常感谢。现在你能不能请你验证我的担忧。实际上计算寄售是调用20000次。而这 20000 次我浪费在从数据库中查询。这意味着现在只有一个查询会进入数据库,对吗?
    • 您是否在$this->calculateConsignment($customer_charge) 方法中执行另一个查询??
    • 我在 customer_charge 上做这就是为什么我问这个而不是每次我可以做一次时都在数据库中查询。这个想法正确吗?
    猜你喜欢
    • 2018-02-09
    • 2016-07-03
    • 2016-12-08
    • 2017-12-20
    • 1970-01-01
    • 2022-10-01
    • 2015-07-06
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多