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

原创
2016-06-06 20:25:22 1372浏览

表的结构如下:

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。