[筆記] Laravel One to Many 遇到 a foreign key constraint fails
碰到錯誤訊息了 (以下 Model 與 Table 名稱為示意,有可能因為手工改寫而有出入,看起來怪怪的地方請跟我說) 在儲存 Category、Product 兩 table 的 One to Many 資料時,我收到的錯誤訊息如下: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`store`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)) (SQL: insert into `products` (`name`, `category_id`) values (商品 P, 0)) 發生錯誤的程式碼簡化後類似這樣: $category = new Category ; $category - > id = "category01" ; $category - > name = "分類 C" ; $category - > save ( ) ; $product = new Product ; $product - > name = "商品 P" ; $category - > products ( ) - > save ( $product ) ; 檢查了一遍 Category 的 Model 已經設好 hasMany : public function products ( ) { return $this - > hasMany ( 'App\Product' ) ; } Product 的 Model 中 belongsTo 也設定正確: public function category ( ) { return $this - > belongsTo ( '