php - 在模型中实现关系

标签 php laravel laravel-5

我有两个模型:DishDishCategory。我决定实现“一对多”关系。 以下是 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/

相关文章:

php - PDO 事务 : What happens to another script

jquery - 使用 AJAX 在 Laravel 中进行实时搜索

mysql - 使用别名格式化 Where 子句的正确方法 - Laravel

php - 按自定义顺序对 Laravel 集合进行排序,而不是 asc 或 desc

php, proc_open 如何传递多个参数

php - CodeIgniter 以错误的顺序执行数据库查询(可能是并行的?)

php - AngularJS:从 Firebug 和用户 session 中隐藏 ajax 数据

laravel - 使用 InstantSearch 显示所有方面

php - 如何从 Crawler filter() 获取单个值?

jquery - 由于 AJAX 请求,Laravel 集合排序无效