简体   繁体   中英

Laravel 5.2 - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

This question has already been asked many times , I went through all the answers, but none solves the error I'm getting.

I'm using Laravel 5.2

I have 2 tables - Classifieds and Categories. When I want to create a classified, I get the error message:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( myclassified . classifieds , CONSTRAINT classifieds_category_id_foreign FOREIGN KEY ( category_id ) REFERENCES categories ( id ))

Migration files defined like this:

for classifieds table:

public function up()
{
    Schema::create('classifieds', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('description');
        $table->string('price');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('classifieds');
}

for categories table:

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('categories');
}

and to add the foreign key,

 public function up()
{
    Schema::table('classifieds', function(Blueprint $table) {
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories');
    });
}

public function down()
{
    Schema::table('classifieds', function(Blueprint $table) {
        $table->dropForeign('classifieds_category_id_foreign');
    });
}

The Models are:

Classified model:

class Classified extends Model
{
   protected $table = 'classifieds';

   protected $fillable = ['title', 'category_id', 'description', 'price'];

   protected $hidden = [];

   public function category(){
       return $this->belongsTo('App\Category');

   }
}

and the Category model:

class Category extends Model
{
   protected $table = 'categories';
   protected $fillable = ['name'];

   protected $hidden = [];

   public function classifieds(){
       return $this->hasMany('App\Classified');
   }
}

and the store method in controller is defined like this:

public function store(Request $request)
{
    $title = $request->input('title');
    $category_id = $request->input('category_id');
    $description = $request->input('description');
    $price = $request->input('price');

    Classified::create([
            'title' =>  $this->title,
            'category_id' => $this->category_id,
            'description' => $this->description,
            'price' => $this->price
    ]);

    return \Redirect::route('classifieds.index')
        ->with('message', 'Ad created');
}

What is my mistake in database set up?

This happens, when you are trying to save Classified and assign the foreign key with an id of category that does not exist yet in Category table.

If you don't have the foreign ID yet, just leave it to be null and make sure you do this on migration to allow null values;

 public function up()
{
    Schema::table('classifieds', function(Blueprint $table) {
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
    });
}

public function down()
{
    Schema::table('classifieds', function(Blueprint $table) {
        $table->dropForeign('classifieds_category_id_foreign');
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM