简体   繁体   English

laravel雄辩地用多个FK进行多对多连接

[英]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. 两种关系都保存在表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. 但是,它抱怨有违反FK的行为。 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. 这是因为attach语句将按顺序处理,并且第一个语句将失败,因为它仅设置类别关系,而类别和文件是同时需要的。

Is it possible to use attach when there are multiple FKs? 有多个FK时可以使用attach吗?

Laravel documentation says you can give additional data to the attach method: Laravel文档说,您可以将其他数据提供给attach方法:

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table: 将关系附加到模型时,您还可以传递要插入到中间表中的附加数据数组:

$user->roles()->attach($roleId, ['expires' => $expires]); $ user-> roles()-> attach($ roleId,['expires'=> $ expires]);

https://laravel.com/docs/5.4/eloquent-relationships#many-to-many https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

In your case: 在您的情况下:

$product->Categories()->attach($category, ['file_id' => $file->id]);

But it seems strange to mix the two relations in one table. 但是将两个关系混合在一个表中似乎很奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM