Laravel 5.6多对多态关系表结构

时间:2018-09-03 11:45:08

标签: php laravel eloquent

我想建立多对多关系表结构。选择的可分类表是枢轴。我正在创建一个类似于下面的表格,但是我不能确定其正确性。

blogs
    id - integer
    name - string
    ...
videos
    id
    video_url

categories
    category_id - integer
    name - string

categorizables
    category_id - integer - unsigned
    categorizable_id - integer -unsigned
    categorizable_type - string - nullable (value likes 'App\Blog' ) 

以下代码属于categorizables表。

public function up()
    {
        Schema::create('categorizables', function (Blueprint $table) {
            $table->unsignedInteger('category_id');
            $table->unsignedInteger('categorizable_id');
            $table->string('categorizable_type');
            $table->timestamps();
            $table->index(['category_id', 'categorizable_id']);
            $table->index(['categorizable_id', 'category_id']);
            $table->index('categorizable_type');
        });
    }

类别迁移文件位于以下

Schema::create('categories', function (Blueprint $table) {
           $table->increments('tag_id');
           $table->string('name');
           $table->string('normalized');
           $table->timestamps();
           $table->index('normalized');
        });

我该如何构建结构?还是要按照我的真实方式行事?

最好的问候

1 个答案:

答案 0 :(得分:1)

想象一下这种结构:

albums
    id
    ...

categories
    id
    ...

album_category
    id
    album_id
    category_id
    ...

一张专辑可以属于几个类别。 一个类别可以属于几张专辑。

比您创建数据透视表来管理此链接。

1)迁移

  • 创建相册表
  • 创建类别表
  • 创建数据透视表:
  

(表名称约定)两个表的名称,按字母顺序,以“ _”分隔

     

(列约定)使用表名和后缀“ _id”的两个外键

     

(时间戳),您可以使用“-> timestamps()”行为添加其他信息


2)相册模型

use Illuminate\Database\Eloquent\Model;

Album extends Model {

   ...

   public function categories()
   {
    return $this->belongsToMany(Category::class);
    // return $this->belongsToMany(Category::class, 'album_category', 'album_id', 'category_id'); // explicit params
    // return $this->belongsToMany(Category::class)->withTimestamps();  // using timestamps
   }

   ...

}

3)类别模型

use Illuminate\Database\Eloquent\Model;

Category extends Model {

   ...

   public function albums()
   {
    return $this->belongsToMany(Album::class);
    // return $this->belongsToMany(Album::class, 'album_category', 'album_id', 'category_id'); // explicit params
    // return $this->belongsToMany(Album::class)->withTimestamps(); // using timestamps
   }

   ...

}

4)测试

// Album
$album = Album::find(1);
dd($album->categories);
// Category
$category = Category::find(1);
dd($category->albums);
相关问题