首页 > 解决方案 > Laravel eloquent 无法输入字段链接具有某个表的外键的数据

问题描述

太奇怪了,我可以从 phpmyadmin 输入数据。但是在使用 eloquent 时出现此错误。

完整性约束违规:1452 无法添加或更新子行:外键约束失败(laravel. medias, CONSTRAINT medias_typeid_foreignFOREIGN KEY ( TypeID) REFERENCES media_types( TypeID))(SQL:插入mediasTitleSynopsis)值(哆啦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
]);

标签: laravel

解决方案


如果下面的代码

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().


推荐阅读