vendredi 22 avril 2016

Laravel Foreing Key Integrity constraint violation

I have two tables in Laravel 5.1 which I created with the following migrations:

class CreateProductsTable extends Migration
{

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->integer('number_of_chapters');
            $table->timestamps();
        });
    }

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

and the second one:

class CreateChaptersTable extends Migration
{

    public function up()
    {
        Schema::create('chapters', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('chapter_id')->unsigned();
            $table->time('input-chapter-start');
            $table->time('input-chapter-end');
            $table->timestamps();
        });

        Schema::table('chapters', function($table) {
            $table->foreign('chapter_id')->references('id')->on('products');
        });
    }

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

My Product Model looks like this:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Product extends Model
    {

        protected $table = 'products';

        protected $fillable = ['email', 'title', input-chapter-start', 'input-chapter-end'];

        public static $rules = [
            'email'                => 'required|email|max:50',
            'title'                => 'required|max:50'
        ];

        public function Chapters()
        {
            return $this->belongsTo('App\Chapters');
        }

        $Chapters = new Chapters;

    }

And my Chapters Model looks like this:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Chapters extends Model
    {

        protected $table = 'chapters';

        protected $fillable = ['input-chapter-start', 'input-chapter-end'];

        public function product()
        {
            return $this->belongsTo('App\Product');
        }
    }

The problem is now that I do not get any values in my chapters table in my database. How do I manage this?

If I try to save the data in my Controller I get following error message:

QueryException in Connection.php line 651: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (html_gen.chapters, CONSTRAINT chapters_chapter_id_foreign FOREIGN KEY (chapter_id) REFERENCES products (id)) (SQL: insert into chapters (updated_at, created_at) values (2016-04-22 11:32:04, 2016-04-22 11:32:04))



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire