php - Laravel eloquent 与查询构建器的优缺点

标签 php mysql laravel eloquent laravel-query-builder

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

示例模型

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

示例表


        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是一种基于查询构建器的扩展方法。它发展到 制作一个简单的源代码,让您更快地编写代码。但对我来说,它不太表达,因为你必须将模型名称设置为表名称。

此外,还有执行时间的比较:

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"]);
    }
});
?>

这证明查询生成器比 Eloquent ORM 快 0.5 秒。

关于php - Laravel eloquent 与查询构建器的优缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58314420/

相关文章:

php - 如何在 PHP < 5.4 中触发 session 垃圾回收?

php - 图书网站条码扫描仪

php - 使用 mysql 和 php 显示 ID 匹配的数据库的单个结果

php - 在 Laravel 应用程序中通过 .htaccess 利用浏览器缓存无法正常工作

javascript - Laravel Redirect::route 不起作用

Javascript日历在再次选择日期时取消选择日期而不是重新选择它

php - Behat:Goutte/Guzzle 通过 cURL "Warning: curl_setopt_array(): 3607 is not a valid File-Handle resource"下载文件

Mysql 优化编辑

java内存不足异常(jdbc)

Laravel 4.1 : proper way to retrieve all morphedBy relations?