laravel为帖子制作类别(规范化表)

时间:2015-01-16 19:41:39

标签: php laravel

Laravel规范化DB中的关系。

所以我的工作表包含工作。和包含类别的类别表。

工作可以有多个类别。

是否有一种平衡关系正常化的方式?

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

但我不确定如何处理,如果我想获得所有$工作的类别,我该怎么办?

如果我想获得$ job类别该怎么办?

是hasOne,还有更适合这个吗?

1 个答案:

答案 0 :(得分:4)

您所描述的是多对多关系。是的,需要像jobs_categories这样的数据透视表。以下是Laravels命名约定和利用关系后如何做到这一点:

数据透视表

jobs_categories很好但是Laravel喜欢category_job(单数和字母顺序)(这样你就不必在你的关系中指定表名)

Schema::create('category_job', function($table){
    $table->increments('id');
    $table->integer('job_id')->unsigned();
    $table->integer('category_id')->unsigned();
    $table->unique(array('job_id', 'category_id'));

    // foreign key constraints are optional (but pretty useful, especially with cascade delete
    $table->foreign('job_id')->references('id')->on('jobs')->onDelete('cascade');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});

关系

工作模式

public function categories(){
    return $this->belongsToMany('Category');
}

类别模型

public function jobs(){
    return $this->belongsToMany('Job');
}

用法

分类为热切加载的作业

$jobs = Job::with('categories')->get();

访问作业的类别

$job = Job::find(1);
$categories = $job->categories;

Visit the Laravel docs for more information on Eloquent relationships