0

每当我做一个 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();  

}
4

2 回答 2

2

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

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

此外,还有一个关于执行时间的比较:

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 秒。

于 2019-10-10T02:32:13.557 回答
1

好吧,选择了答案,但我只想表明,与 Query Builder 相比,eloquent 并没有那么慢。我们需要的只是技术。

用下面的技巧,你的 Eloquent 快了很多。

<?php

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

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

于 2021-12-31T04:39:27.007 回答