laravel6.0外键约束注意事项

现在laravel6.0以上默认生成的ID项目是bigIncrements格式,但是如果想模型关联需要改为increments格式!【谨记】

public function up()
    {
    
    
        Schema::create('classifies', function (Blueprint $table) {
    
    
            $table->increments('id');
            $table->string('name')->comment('栏目名称');
            $table->string('introduce')->comment('栏目介绍');
            $table->integer('rank')->default('0')->comment('等级|0.顶级ID为0 1.二级ID为顶级ID');
            $table->integer('state')->default('1')->comment('状态|1.正常 2.屏蔽');
            $table->timestamps();
        });
    }

下面则是外键的匹配表

public function up()
    {
    
    
        Schema::create('classify_notices', function (Blueprint $table) {
    
    
            //注意要外键关联不能用bigIncrements而要用increments
            $table->increments('id');
            $table->string('title')->comment('公告名称');
            //因为作为主键的id值是从1开始自增的,所以在被其绑定的外键字段的数据类型就不能使用integer,而要改用unsignedInteger
            $table->unsignedInteger('classify_id')->comment('公告所属分类');
            // $table->foreign('被约束的字段')->references('约束的字段')->on('约束的表名')->onDelete('受此约束删除');
            $table->foreign('classify_id')->references('id')->on('classifies')->onDelete('cascade');
            //nullable()可以为空
            $table->string('keyword')->nullable()->comment('关键字|SEO');
            $table->text('bewrite')->nullable()->comment('描述|SEO');
            $table->string('thumb')->comment('缩略图|image');
            $table->integer('click')->comment('查看次数|input');
            $table->mediumtext('content')->comment('内容|simditor');
            $table->tinyInteger('iscommend')->default(2)->comment('推荐|radio|1:是,2:否');
            $table->integer('state')->default('1')->comment('状态|1.正常 2.屏蔽');
            $table->timestamps();
        });
    }

laravel外键必须是同类型的字段才能匹配!

猜你喜欢

转载自blog.csdn.net/lo6064200/article/details/104669121