>  기사  >  백엔드 개발  >  Laravel怎么在Model定义复合主键。

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

WBOY
WBOY원래의
2016-06-06 20:25:221743검색

表的结构如下:

<code>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</code>

需要用Eloquent ORM的save()方法,他会根据primaryKey来保存数据,请问如何在Model设置这种复合主键?

<code>/**
 * The primary key for the model.
 *
 * @var string
 */
protected $primaryKey = 'id';</code>
<code>$cart = Cart::firstOrNew([...]);
$cart->quantity = $quantity;
$cart->save();
</code>

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'

回复内容:

表的结构如下:

<code>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</code>

需要用Eloquent ORM的save()方法,他会根据primaryKey来保存数据,请问如何在Model设置这种复合主键?

<code>/**
 * The primary key for the model.
 *
 * @var string
 */
protected $primaryKey = 'id';</code>
<code>$cart = Cart::firstOrNew([...]);
$cart->quantity = $quantity;
$cart->save();
</code>

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으로 문의하세요.