lundi 25 avril 2016

Laravel 5.1 Foreign Key Trouble

I have some trouble getting the foreign key.

My Migrations looks like this (shortened them):

    <?php

    class CreateProductsTable extends Migration
    {
        public function up()
        {


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

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

<?php

    class CreateChaptersTable extends Migration
    {

        public function up()
        {
            Schema::create('chapters', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('product_id')->unsigned();   
                $table->time('input-chapter-start1');
                $table->time('input-chapter-end1');
                $table->timestamps();

            });

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

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

And my 2 Model like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Chapters extends Model
{

    protected $table = 'chapters';

    protected $fillable = ['input-chapter-start1', 'input-chapter-end1'];

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

}
<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Product extends Model
    {

        protected $table = 'products';

        protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];

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

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

    }

And just save it like this in my Controller

$product->save();
$Chapters->save();

And get following error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (generator.chapters, CONSTRAINT chapters_product_id_foreign FOREIGN KEY (product_id) REFERENCES products (id)) (SQL: insert into chapters (input-chapter-start1, input-chapter-end1, updated_at, created_at) values (12:12:12, 12:12:12, 2016-04-25 11:41:31, 2016-04-25 11:41:31))



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire