【发布时间】:2015-01-17 03:53:17
【问题描述】:
数据库中的 Laravel 规范化关系。
所以我有一个包含工作的工作表。以及包含类别的类别表。
工作可以有多个类别。
有没有一种简单的方法可以使关系正常化?
Schema::create('jobs', function($table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->string('title');
$table->string('excerpt')->nullable();
$table->text('content');
$table->integer('delivery');
$table->integer('price');
$table->unique(array('user_id', 'slug'));
$table->timestamps();
});
Schema::create('categories', function(Blueprint $table)
{
// These columns are needed for Baum's Nested Set implementation to work.
// Column names may be changed, but they *must* all exist and be modified
// in the model.
// Take a look at the model scaffold comments for details.
// We add indexes on parent_id, lft, rgt columns by default.
$table->increments('id');
$table->integer('parent_id')->nullable()->index();
$table->integer('lft')->nullable()->index();
$table->integer('rgt')->nullable()->index();
$table->integer('depth')->nullable();
// Add additional columns here (f.ex: name, slug, path, etc.)
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('description')->nullable();
});
我的第一反应是创建一个保存关系的中间表:
Schema::create('jobs_categories', function($table)
{
$table->increments('id');
$table->integer('job_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->unique(array('job_id', 'category_id'));
});
但我不知道该怎么做,如果我想获取所有 $jobs 的类别,我该怎么办?
如果我想获得 $job 类别该怎么办?
hasOne、hasMany 更适合这个吗?
【问题讨论】:
-
视情况而定。一个工作可以有多个类别。同一个类别可以属于多个职位吗?
-
@user3158900 是的,为什么不呢?帖子有很多分类,分类有很多帖子。
-
lukasgeiter 有一个很好的答案,所以我不会费心创建另一个,但我要补充的唯一一点是 Laravel 期望数据透视表是单数并按字母顺序排列。只需将
jobs_categories更改为category_job -
@user3158900 你看过我的回答了吗? (数据透视表部分的第一句话);)