0
votes

It so weird, i can input data from phpmyadmin. but i get this error when using eloquent.

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (laravel.medias, CONSTRAINT medias_typeid_foreign FOREIGN KEY (TypeID) REFERENCES media_types (TypeID)) (SQL: insert into medias (Title, Synopsis) values (doraemon, travel to the world))

json data

{
    "type_id": "3",
    "title": "doraemon",
    "synopsis": "travel to the world"
}

medias table

$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';

media types table

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'] 
]);

store function

Media::create([
            'TypeID'    => $request->type_id,
            'Title'     => $request->title,
            'Synopsis'  => $request->synopsis
]);
1

1 Answers

1
votes

If the following code

Media::create([
    'TypeID'    => $request->type_id,
    'Title'     => $request->title,
    'Synopsis'  => $request->synopsis
]);

produces this SQL (according to your error message):

insert into medias (Title, Synopsis) values (doraemon, travel to the world)

Then you probably don't have TypeID in your $fillable properties in the Media model

class Media extends Model
{
    protected $fillable = [
        'TypeID',
        'Title',
        'Synopsis',
    ];
}

Also, unless you have a media_types row with TypeID = 0, that ->default(0) in the medias migration is bound to cause more errors. If you want to make medias.TypeID optional, instead of ->default(0) use ->nullable().