laravel - Laravel eloquent 无法输入字段链接具有某个表的外键的数据
问题描述
太奇怪了,我可以从 phpmyadmin 输入数据。但是在使用 eloquent 时出现此错误。
完整性约束违规:1452 无法添加或更新子行:外键约束失败(
laravel
.medias
, CONSTRAINTmedias_typeid_foreign
FOREIGN KEY (TypeID
) REFERENCESmedia_types
(TypeID
))(SQL:插入medias
(Title
,Synopsis
)值(哆啦A梦,环游世界))
json数据
{
"type_id": "3",
"title": "doraemon",
"synopsis": "travel to the world"
}
媒体表
$table->mediumIncrements('MediaID');
$table->unsignedSmallInteger('TypeID')->default('0');
$table->string('Title', 255);
$table->text('Synopsis')->nullable();
$table->foreign('TypeID')->references('TypeID')->on('media_types');
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
媒体类型表
Schema::create('media_types', function (Blueprint $table) {
$table->smallIncrements('TypeID');
$table->string('Typename', 100);
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
DB::table('media_types')->insert([
['TypeName' => 'Movie'],
['TypeName' => 'Tv show'],
['TypeName' => 'Comic']
]);
存储功能
Media::create([
'TypeID' => $request->type_id,
'Title' => $request->title,
'Synopsis' => $request->synopsis
]);
解决方案
如果下面的代码
Media::create([ 'TypeID' => $request->type_id, 'Title' => $request->title, 'Synopsis' => $request->synopsis ]);
生成此 SQL(根据您的错误消息):
insert into medias (Title, Synopsis) values (doraemon, travel to the world)
那么您可能在模型的$fillable
属性中没有 TypeIDMedia
class Media extends Model
{
protected $fillable = [
'TypeID',
'Title',
'Synopsis',
];
}
此外,除非您有media_types
一行 TypeID = 0,否则迁移->default(0)
中medias
必然会导致更多错误。如果你想成为medias.TypeID
可选的,而不是->default(0)
使用->nullable()
.
推荐阅读
- r - 来自在输出中分离的表的卡方
- javascript - Mongodb shell:使用javascript逻辑修改集合中的每个元素
- javascript - 自firefox 68以来如何在javascript中的同一目录中获取文件
- multithreading - common lisp如何管理cpu资源和同步线程
- git - 将私有 github 存储库设置为 docker 中 package.json 中的依赖项在 github 操作中生成失败
- python - 如何在python中的一个图形上绘制许多kdeplots
- reactjs - react-router 路由中基于路由的测试的推荐方法
- python - 如何修改数据以在另一个时间可验证的特定范围内删除 id
- php - 取消订阅 PHP 和 SMTP 脚本
- java - 无法访问 com.amazonaws.protocol.StructuredPojo