表的結構如下:
REATE TABLE `carts` ( `user_id` int(10) unsigned NOT NULL, `product_id` char(64) NOT NULL, `quantity` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`user_id`,`product_id`), KEY `fk_idx_cart_product` (`product_id`), CONSTRAINT `fk_idx_cart_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`), CONSTRAINT `fk_idx_cart_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
需要用Eloquent ORM的save()方法,他會根據primaryKey來儲存資料,請問如何在Model設定這種複合主鍵?
/** * The primary key for the model. * * @var string */protected $primaryKey = 'id';
$cart = Cart::firstOrNew([...]);$cart->quantity = $quantity;$cart->save();
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
回複內容:
表的結構如下:
REATE TABLE `carts` ( `user_id` int(10) unsigned NOT NULL, `product_id` char(64) NOT NULL, `quantity` int(10) unsigned NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`user_id`,`product_id`), KEY `fk_idx_cart_product` (`product_id`), CONSTRAINT `fk_idx_cart_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`), CONSTRAINT `fk_idx_cart_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
需要用Eloquent ORM的save()方法,他會根據primaryKey來儲存資料,請問如何在Model設定這種複合主鍵?
/** * The primary key for the model. * * @var string */protected $primaryKey = 'id';
$cart = Cart::firstOrNew([...]);$cart->quantity = $quantity;$cart->save();
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
這個問題沒有解決,大部分別的架構也沒有解決,所以暫時沒有辦法在Eloquent ORM 定義複合主鍵,解決辦法:
1.使用doctrine。
2.在表單驗證裡面做驗證,也能達到主鍵約束的效果。
關於這個問題其實在一年前就有國外的程式員在github上提了issue的,並且taylorotwell還參與了討論,他給出的回複是laravel目前沒有計劃增加這個功能。直到今天(2015.11.07)都沒有這個功能。詳情請見以下連結:https://github.com/laravel/framework/issues/5355