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();
}