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