我有两个模型:Dish 和 DishCategory。我决定实现“一对多”关系。 以下是 Dish 模型的迁移:
Schema::create('dishes', function (Blueprint $table) {
$table->increments('id');
$table->string('dish', 50);
$table->string('photo');
$table->double('price', 8, 2);
$table->integer('category_id');
$table->integer('type_id'); /* 1 - menu for delivery; 0 - general menu */
});
DishCategory 模型的迁移:
Schema::create('dish_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category');
});
我在 DishCategory 模型中创建了一个名为 dish()
的方法:
public function dish()
{
return $this->hasMany('App\Dish');
}
以及 Dish 模型中的 dish_category()
:3
public function dish_category()
{
return $this->belongsTo('App\DishCategory', 'category_id');
}
我正在尝试在我的关系中设置外键,因此已在 dish_category()
方法中将其设置为 belongsTo()
的第二个参数。但这不起作用。解决方法是什么?
最佳答案
将 dish()
关系定义更改为:
public function dish()
{
return $this->hasMany('App\Dish', 'category_id');
}
并且 dish_category()
定义正确。
如果您还想添加constraint ,将其添加到 dishes
表迁移中:
Schema::table('dishes', function (Blueprint $table) {
$table->foreign('category_id')->references('id')->on('dish_categories');
});
关于php - 在模型中实现关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619556/