首页 > Laravel怎么在Model定义复合主键。

Laravel怎么在Model定义复合主键。

表的结构如下:

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

【热门文章】
【热门文章】