簡體   English   中英

laravel雄辯地用多個FK進行多對多連接

[英]laravel eloquent many to many attach with multiple FKs

我有四個表:

categories
id, name

products
id, name

files
id, location

category_product
id, cateogry_id, product_id, file_id

產品和類別之間以及產品和文件之間存在許多關系。 兩種關系都保存在表category_product中。 我還設置了適當的模型,現在想創建關聯:

$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);

但是,它抱怨有違反FK的行為。 這是因為attach語句將按順序處理,並且第一個語句將失敗,因為它僅設置類別關系,而類別和文件是同時需要的。

有多個FK時可以使用attach嗎?

Laravel文檔說,您可以將其他數據提供給attach方法:

將關系附加到模型時,您還可以傳遞要插入到中間表中的附加數據數組:

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

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

在您的情況下:

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

但是將兩個關系混合在一個表中似乎很奇怪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM