andersao / l5-repository

Laravel 5 - Repositories to abstract the database layer
http://andersao.github.io/l5-repository
MIT License
4.19k stars 876 forks source link

Save model with one-to-many relation #132

Closed gjportegies closed 8 years ago

gjportegies commented 8 years ago

I'm struggling with the following problem, I have a product model that looks like this:

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('attribute_set_id')->unsigned();

    $table->string('slug');
    $table->string('name');
    $table->text('intro');
    $table->text('text'); 
    $table->string('meta_title');
    $table->string('meta_description');
    $table->string('meta_keywords');
    $table->double('price');
    $table->integer('sequence');
    $table->tinyInteger('active');
    $table->timestamps();

    $table->foreign('attribute_set_id')->references('id')->on('attribute_sets')->onDelete('cascade');
});

Now I'm trying to save my model in my controller like this:

$product = $this->productRepository->create(Input::all());

This is the die and dump from the input:

array:10 [▼
  "_token" => "Vd9mMDCOJNVlcGD0EeJkGZMJjkbHsfAiazTZg5vv"
  "attribute_set_id" => "1"
  "categories" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "name" => "test"
  "intro" => "<p>test</p>\r\n"
  "text" => "<p>testt</p>\r\n"
  "price" => "10.00"
  "meta_title" => "test"
  "meta_description" => "test"
  "meta_keywords" => "test"
]

But I'm getting the following 'Integrity constraint violation' error because the product requires a one-to-many relation with the attribute_set table. How can solve this?

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`cms_v1.1`.`products`, CONSTRAINT `products_attribute_set_id_foreign` FOREIGN KEY (`attribute_set_id`) REFERENCES `attribute_sets` (`id`) ON DELETE CASCADE) (SQL: insert into `products` (`price`, `updated_at`, `created_at`) values (10.00, 2016-01-29 08:56:30, 2016-01-29 08:56:30))

Without the use of repositories I would simply do it like this:

$set = AttributeSet::find(Input::get('attribute_set_id'));

$product = Product::create(Input::all());
$product->attributeSet()->associate($set);
$product->save();
gjportegies commented 8 years ago

Problem was caused because the column 'attribute_set_id' was not mass assignable. My bad.