Laravel 建表
public function up()
{
Schema::create('user_favorite_products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->comment('用户id');
// 外键
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('product_id')->comment('产品id');
// 外键
/**
* @ onDelete('cascade')
* on update 和 on delete 后面可以跟的词语有四个
* no action , set null , set default ,cascade
* no action 表示 不做任何操作,
* set null 表示在外键表中将相应字段设置为null
* set default 表示设置为默认值
* @ cascade 表示级联操作,就是说,如果主键表中被参考字段更新,外键表中也更新,主键表中的记录被删除,外键表中改行也相应删除
*
* @ references('id')
* 外键约束定义外键的方法
* 方法1:列名+ references 主表(列名)
* 方法2: constraint 逻辑名 foreign key(列名) references 主表(列名)
* @ 方法3: foreign key references 主表(列名)
*
* ON DELETE、ON UPDATE表示事件触发限制,可设参数:
* RESTRICT(限制外表中的外键改动)
* CASCADE(跟随外键改动)
* SET NULL(设空值)
* SET DEFAULT(设默认值)
* NO ACTION(无动作,默认的)
*/
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamps();
});
// 表注释
DB::statement("ALTER TABLE `shopping`.`user_favorite_products` comment='用户收藏中间表'");
}
推荐文章: