laravel - 无法使用外键添加新列
问题描述
我是 laravel 的新手,向现有表添加新列时出现上述错误:
SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
schoolmanagement
.#sql-314_2c
,CONSTRAINTstudents_parentsid_foreign
FOREIGN KEY (parentsid
) REFERENCESparent_names
(id
) ON DELETE CASCADE)(SQL:alter tablestudents
add constraintstudents_parentsid_foreign
foreign key (parentsid
) 引用parent_names
(id
) 删除级联)
在
public function up(){
Schema::table('students', function (Blueprint $table)
{
$table->unsignedBigInteger('parentsid')->after('id');
$table->foreign('parentsid')->references('id')->on('parent_names')->onDelete('cascade');
});
}
public function down()
{
Schema::table('students', function (Blueprint $table) {
//
});
}
只需使用外键为现有表插入一列
解决方案
那是因为您试图创建一个具有外键约束但没有设置默认值的新列。因此,您可以将其设置为nullable
或设置默认值(必须是parent_names
表中存在的 ID)
$table->unsignedBigInteger('parentsid')->default(1);
推荐阅读
- django - Django ForeignKey 反向查询
- wpf - 如何正确实现 XAML INotifyPropertyChanged 以防止 GDI 泄漏
- gitlab - Gitlab shell runner 无法上传大于 63KB 的工件:“501 未实现”
- python - 应用 minmaxscaler 后,列中的 Pandas 科学形式值给出错误的输出
- r - 如何通过第二个 col 中的最大值找到第一个 col 值(在矩阵中)
- python - 将文本字符串拆分为 int 和 text 变量
- sql-server - 在 Azure Functions 上使用 Microsoft 报表查看器
- javascript - 如何在 React 中将 connect() 和 withStyles() 用于类组件?
- php - 如何从 Codeigniter 中的返回结果运行多个查询
- scala - 如果我修改指向缓存 rdd 的变量会发生什么?