I have one foreign key in my database named images.
This is its Migration:
class CreateImagesTable extends Migration
{
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('product_r_id')->unsigned();
$table->string('name', 50);
$table->text('images', 50);
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
Schema::table('images', function (Blueprint $table) {
$table->foreign('product_r_id')->references('id')->on('products_r')->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::drop('images');
}
}
Its Model looks like this:
class Images extends Model
{
protected $table = 'images';
protected $fillable = ['product_id', 'product_r_id', 'name', 'images'];
public function product()
{
return $this->belongsTo('App\Product', 'product_id');
}
public function productR()
{
return $this->belongsTo('App\ProductR', 'product_r_id');
}
}
ProductR Model looks like this:
class ProductR extends Model
{
protected $table = 'products_r';
protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];
public function images()
{
return $this->hasMany('App\Images');
}
}
And Product Model like this:
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];
public function scenesImages()
{
return $this->hasMany('App\Images');
}
}
So I basicaly try to save in two different forms different products with their image into the same table in my database (images).
Running my Program returns me this error:
QueryException in Connection.php line 655: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
mydb.images, CONSTRAINTimages_product_id_foreignFOREIGN KEY (product_id) REFERENCESproducts(id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert intoimages(name,images,product_r_id,updated_at,created_at) values (ki, 0Chrysanthemum.jpg, 10, 2016-05-20 10:50:51, 2016-05-20 10:50:51))