博客网站开发指南1:migration

发布时间 2023-12-06 15:58:44作者: Laravel自学开发

文章表设计

下面是一个示例的迁移设计,用于创建博客文章表:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticlesTable extends Migration
{
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->unsignedBigInteger('author_id');
            $table->unsignedBigInteger('category_id');
            $table->timestamps();

            $table->foreign('author_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

在这个示例中,articles 表包含以下字段:

  • id:主键 ID。
  • title:文章标题。
  • content:文章内容。
  • author_id:作者对应的用户 ID,与 users 表进行外键关联。
  • category_id:文章分类对应的分类 ID,与 categories 表进行外键关联。
  • timestamps():自动维护的创建时间和更新时间字段。

在迁移文件中,我们使用了 foreign() 方法来定义外键关系。onDelete('cascade') 选项表示当关联的用户或分类被删除时,对应的文章也会被自动删除。

此外,您还可以创建额外的迁移文件来创建关联的标签表、点赞表和收藏表。这些表可以与 articles 表进行关联,并使用外键来建立关系。

希望这个示例对您有所帮助!如果您需要更多的帮助,请随时提问。

标签设计

如果您希望文章可以添加多个标签,可以使用多对多关系来实现。以下是一个示例的迁移设计,用于创建文章表、标签表和它们之间的关联表:

首先,创建迁移文件来创建标签表:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTagsTable extends Migration
{
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('tags');
    }
}

接下来,创建迁移文件来创建文章和标签之间的关联表:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticleTagTable extends Migration
{
    public function up()
    {
        Schema::create('article_tag', function (Blueprint $table) {
            $table->unsignedBigInteger('article_id');
            $table->unsignedBigInteger('tag_id');
            $table->timestamps();

            $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');

            $table->primary(['article_id', 'tag_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('article_tag');
    }
}

在这个示例中,tags 表包含标签的信息,article_tag 表用于关联文章和标签。article_tag 表包含以下字段:

  • article_id:文章 ID,与 articles 表进行外键关联。
  • tag_id:标签 ID,与 tags 表进行外键关联。
  • timestamps():自动维护的创建时间和更新时间字段。

使用 primary(['article_id', 'tag_id']) 方法将 article_idtag_id 列定义为联合主键,确保每个文章和标签的组合是唯一的。

通过这种多对多关系,每篇文章可以与多个标签相关联,每个标签也可以与多篇文章相关联。

希望这个示例对您有所帮助!如果您有其他问题,请随时提问。