Monday, March 20, 2017

laravel eloquent many to many attach with multiple FKs

I have four tables:

categories
id, name

products
id, name

files
id, location

category_product
id, cateogry_id, product_id, file_id

There are many to many relationships between product and category, as well as product and file. Both relationships are saved in the table category_product. I have also setup the appropriate models and would now like to create the associations:

$category = new Category();
$category->name = "Electronics";
$category->save();

$file = new File();
$file->location = "some\path";
$file->save();

$product = new Product();
$product->save()
$product->Categories()->attach($category);
$product->Files()->attach($file);

However, it complains that there is a FK violation. This is because the attach statements are processed sequentially and the first one will fail because it only sets the category relationship, while category and file are required at the same time.

Is it possible to use attach when there are multiple FKs?



via Chris

Advertisement