The table structure is as follows: {code...} needs to use the save () method of EloquentORM to save data based on primaryKey. How can I set this composite primary key in Model? {Code...} SQLSTATE [42S22]: Columnnotfound: 1054 Unknowncolumn & #039;... the table structure is as follows:
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
We need to use the save () method of Eloquent ORM to save data based on primaryKey. How can we set this composite primary key in 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'
Reply content:
The table structure is as follows:
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
We need to use the save () method of Eloquent ORM to save data based on primaryKey. How can we set this composite primary key in 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'
This problem has not been solved, and most other frameworks have not solved it. Therefore, there is no way to define a composite primary key in Eloquent ORM. solution:
1. Use doctrine.
2. Verification in form verification can also achieve the effect of primary key constraints.
In fact, a foreign programmer mentioned issue on github a year ago, and taylorotwell also participated in the discussion. His reply is that laravel is not planning to add this function at present. This feature is unavailable until today (2015.11.07. For more information, see the following link: https://github.com/laravel/framework/issues/5355