Laravel 违反外键完整性约束

Laravel Foreign Key Integrity constraint violation

我的数据库中有一个名为 images 的外键。

这是它的迁移:

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

}

它的模型是这样的:

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 模型如下所示:

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

}

产品型号是这样的:

class Product extends Model
{
    protected $table = 'products';

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

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

所以我基本上尝试以两种不同的形式将不同的产品及其图像保存到我的数据库(图像)中的相同table。

运行 我的程序 returns 我这个错误:

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, CONSTRAINT images_product_id_foreign FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into images (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))

我认为问题的出现是因为这些行:

$table->integer('product_id')->unsigned();
[...]
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade')->onUpdate('cascade');

你不能不填写就创建图像 product_id 这似乎是因为错误

insert into images (name, images, product_r_id, updated_at, created_at) ...

表明您正在插入到 images 中而没有 product_id,它不能为 null 并且具有外键约束。

我想你可以做一个

$table->integer('product_id')->unsigned()->nullable();

所以插入的时候不需要赋值