Laravel eloquent vs 查询生成器优缺点

Laravel eloquent vs query builder pros and cons

每当我做一个 laravel 项目时,我总是不仅在模型中而且在数据库中定义关系(我总是做一个 php artisan make:model ModelName -mcr)。有时我看到代码只定义了模型中的关系,而不是数据库中的关系,反之亦然。有人能告诉我它们有什么区别吗?我应该始终在模型和数据库中定义关系,还是应该在其中之一中定义关系?此外,我总是同时使用 laravel eloquent 查询和 laravel 查询构建器,即 DB::table。使用两者的优点和缺点是什么?哪个更快?告诉我你的意见和建议。我希望你明白我的意思。谢谢

示例模型

public function damage(){
        return $this->hasMany('App\Product');
    }

样本Table


        Schema::table('damages', function($table)
        {
            $table->foreign('product_id')
                    ->references('id')
                    ->on('products')
                    ->onDelete('cascade');
        });

示例查询

  public function getDamages(){
        $damages = DB::select(
            "SELECT damages.product_id, damages.quantity, damages.price, products.product_name
            FROM damages
            JOIN products on damages.product_id = products.id"
           );
        return view('damages', compact('damages'));

//or

 $recipes = DB::table('recipes')
            ->join('category_recipe', 'recipes.id', '=', 'category_recipe.recipe_id')
            ->join('category', 'category.id', '=', 'category_recipe.category_id')
            ->join('users', 'users.id', '=', 'recipes.user_id')
            ->where('category.id', '=', $cat_id)->get(array('recipes.*','users.*'));  

    }

示例查询 2

public function index(){
       $damage = Damage::all();
//or
       $suppliers = Supplier::all()->where('status', 'active');
//or
       $recipes = Recipe::with('category')->where('category_id',$cat_id)->get();  

}

基于这篇文章: https://kursuswebprogramming.com/perbedaan-eloquent-dan-query-builder-laravel/

Eloquent ORM是一个基于Query builder的扩展方法。它发展到 制作一个简单的源代码,让你更快地编写你的代码。但对我来说,它太不表达了,因为你必须将你的模型名称设置为 table 名称。

还有执行时间的比较:

Eloquent ORM(执行时间:1.41 秒,执行的查询数:1000)

<?php

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

查询生成器(执行时间:938 毫秒,执行的查询数:1000)

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

这证明 Query Builder 比 Eloquent ORM 快 0.5 秒。

好吧,答案已选,但我只是想证明 eloquent 与查询生成器相比并没有那么慢。我们需要的只是技术。

下面的机智技巧,你的Eloquent快多了。

<?php

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

Eloquent 是为了可读性而设计的,它会牺牲一点性能,但如果你正确使用它,不会有太大影响。 对于长期项目,了解导致问题的代码并快速修复它的能力比比 10k 记录查询生成器慢 1 秒更重要。 至少我是这么认为的。