laravel 为 post 分类(规范化 table)

laravel making categories for a post (normalizing table)

Laravel 规范化数据库中的关系。

所以我有包含作业的作业 table。以及包含类别的类别 table。

职位可以有多个类别。

有没有一种正常化关系的方法?

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

我的第一直觉是创建一个中介 table 来保持关系:

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 更适合这个吗?

您描述的是多对多关系。是的,需要像 jobs_categories 这样的枢轴 table。以下是遵循 Laravel 命名约定并利用关系的方法:

枢轴table

jobs_categories 很好,但 Laravel 喜欢 category_job(单数和字母顺序)(这样您就不必在关系中指定 table 名称)

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