简体   繁体   English

Laravel 处理多个查询和连接的最佳实践

[英]Laravel Best Practice in handling Multiple Queries and Joins

I need a code suggestion.我需要一个代码建议。

Basically I'm developing a system that requires a lot of joins and relationship in the database.基本上我正在开发一个需要在数据库中进行大量连接和关系的系统。 Currently in Laravel I'm using Query Builder for Database queries in the application.目前在 Laravel 中,我在应用程序中使用查询生成器进行数据库查询。

Currently I have this example of Querying in the database.目前我在数据库中有这个查询示例。

 $approved = DB::table('employee_overtimes as eo')
            ->select('eo.id as id', 'eo.employee_id as eo_employee_id', 'eo.overtime_date', 'eo.time_in', 'eo.time_out', 'eo.approver_id', 'eo.remarks', 'eo.status',
                'firstname','lastname','employee.employee_no', 'employee.id as employee_id', 'eo.created_at')
            ->join('employee' , 'employee.id', '=', 'eo.employee_id')
            ->where('eo.status', '=', 'Approved')
            ->orderByDesc('eo.created_at')
            ->orderBy('lastname', 'ASC')
            ->get();

Can Anyone suggest a better approach in handling this kind of queries?任何人都可以提出更好的方法来处理此类查询吗? Because it becoming repetitive in my controller.因为它在我的 controller 中变得重复。

Its okay to use the querybuilder instead of eloquent because it is more faster and sometimes eloquent cant handle complex queries.可以使用查询构建器代替 eloquent,因为它更快,有时 eloquent 无法处理复杂的查询。 And also, avoid using DB::raw because it is prone to sql injections.此外,避免使用DB::raw ,因为它容易被 sql 注入。 Please refer to this article https://kursuswebprogramming.com/perbedaan-eloquent-dan-query-builder-laravel/请参考这篇文章https://kursuswebprogramming.com/perbedaan-eloquent-dan-query-builder-laravel/

And for your concern about the repetitive code, you must create your custom function or library and then you can use it in each of your controller as you wish.对于重复代码的担忧,您必须创建自定义 function 或库,然后您可以根据需要在每个 controller 中使用它。

Let me show you some comparison让我给你看一些比较

Eloquent ORM (Execution time: 1.41 s, Queries Executed: 1000) Eloquent ORM(执行时间:1.41 s,查询次数:1000)

<?php

Route::get("test",function(){
    for($i=0;$i<1000;$i++){
         $t=new Country();
         $t->label=$i." Row";
         $t->save();
    }
}); 
?>

Query Builder (Execution time: 938 ms, Queries Executed: 1000)查询生成器(执行时间:938 毫秒,执行的查询:1000)

<?php
Route::get("test",function(){
    for($i=0;$i<1000;$i++){
         DB::table("countries")->insert(["label"=>$i." Row"]);
    }
});
?>

Now this is a prove that Query Builder is 0.5 s faster than Eloquent.现在这证明查询生成器比 Eloquent 快 0.5 秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM