Php 重构Laravel函数以减少数据库查询数量

Php 重构Laravel函数以减少数据库查询数量,php,laravel,eloquent,laravel-5.2,Php,Laravel,Eloquent,Laravel 5.2,我想知道是否有人能给我一些关于重构以下函数以减少数据库查询数量的建议?或者,使用Laravel可能有一种完全不同的方法来实现这一点 我试图计算一项工作的损益,该工作由产品组成,产品由组件组成: public function jobProfitAndLoss($id) { $products_in_job = DB::table('job_product') ->where('job_id', $id) ->get();

我想知道是否有人能给我一些关于重构以下函数以减少数据库查询数量的建议?或者,使用Laravel可能有一种完全不同的方法来实现这一点

我试图计算一项工作的损益,该工作由产品组成,产品由组件组成:

public function jobProfitAndLoss($id)
{
    $products_in_job = DB::table('job_product')
            ->where('job_id', $id)
            ->get();

    $total_price = 0.0000;
    $total_cost = 0.0000;

    foreach ($products_in_job as $row) {
        $total_price = $total_price + ($row->quantity)*($row->price);

        $product_id = $row->product_id;

        $components_in_product = DB::table('components')
            ->where('product_id', $product_id)
            ->get();

        foreach ($components_in_product as $component) {
            $total_cost = $total_cost + ($component->cost)*($row->quantity);
        }

    }

    return $total_price-$total_cost;

}
产品包含以下组件:

组件属于以下产品—

乔布斯有很多产品-

您将在这里看到,有一些相同的查询被多次执行,我不知道在这种情况下如何避免-


非常感谢您的帮助

Edit:似乎您没有使用模型。如果尚未这样做,请为数据库条目创建模型。您需要为
job\u product
使用
protected$table
属性,因为Eloquent可能无法自动将类名转换为正确的表名

首先,如果你还没有建立关系,那就建立关系。例如,在
Job.php
下,包括产品关系:

public function products() {
    return $this->hasMany(App\Products::class); // Assuming App is the namespace
}
现在,您可以直接执行
$components\u in\u product=$products\u in\u job->products。但是,这仍然会导致N+1查询

因此,请看以下内容:

对于此操作,将只执行两个查询:

select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)

因此,将job中的
$products\u更改为雄辩的查询,并将
->with('products')
添加到查询中。

我已经设置了所有模型(作业、产品、组件)及其关系。好的。在这种情况下,这只是一个切换到雄辩和使用
->与('products')
,然后引用
$row->products
@TomHoad作为参考,称为“急切加载”。你可以在报纸上看到。
select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)