0

Whenever I make a laravel project, I always define relationships not just in the model but also in the database (I always do a php artisan make:model ModelName -mcr). Sometimes I saw code that they only define relationships in model but not in the database and vice versa. Can someone tell me what are their differences and should I always define relationships in the model and in the database or should I do in one of them? Also, I always use both laravel eloquent queries and laravel query builder which is DB::table. What are the pros and cons of using both? Which are faster? Tell me your opinions and advice. I hope you get my point. Thanks

Sample Model

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

Sample Table


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

Sample query

  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.*'));  

    }

Sample query 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();  

}
draw134
  • 1,053
  • 4
  • 35
  • 84
  • 1
    isnt that two questions..? you should define relationship in table or laravel migration to keep database consistency. both eloquent and query builder is usable and safe (as long as you stay away from using `DB::raw` with string concatenation, use [proper binding](https://stackoverflow.com/a/28430886/4648586)). – Bagus Tesa Oct 10 '19 at 02:02
  • why should i stay away from using `DB::raw` sir? Is that bad? – draw134 Oct 10 '19 at 02:03
  • 1
    as stated in the [laravel documentation](https://laravel.com/docs/5.8/queries#raw-expressions), be wary of `DB::raw` as you might accidentally allow [sql injection](https://www.owasp.org/index.php/SQL_Injection) on your website, which is bad. – Bagus Tesa Oct 10 '19 at 02:04
  • ohh i see sir. thanks for the info. – draw134 Oct 10 '19 at 02:07

2 Answers2

2

Based on this article : https://kursuswebprogramming.com/perbedaan-eloquent-dan-query-builder-laravel/

Eloquent ORM is an extended method based on Query builder. It developed to make a simple source code, make and you faster to write your code. But for me it's so less expressif cause you have to set your model name as table name.

And also, there is an comparison about execution time :

Eloquent ORM (Execution time : 1.41 s, Queries Executed : 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)

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

This is a prove Query Builder is 0.5 s faster than Eloquent ORM.

1

Well, the answer is chosen but I just want to show that eloquent is not that slow compared to Query Builder. All we need is technique.

Wit technique bellow, your Eloquent is a lot faster.

<?php

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

Eloquent is made for readably and it sacrifices a little bit performance but not much if you use it correctly. For long term project, the ability to understand which code cause the problem and fix it quickly is more important than 1 second slower than a 10k records Query Builder. At least it's my thought.

lyhong
  • 947
  • 1
  • 13
  • 23