gpt4 book ai didi

php - 用额外的字段保存 HABTM?

转载 作者:行者123 更新时间:2023-11-30 23:10:55 25 4
gpt4 key购买 nike

我正在尝试保存订单和订单中的产品。

正在保存订单,但没有保存产品。

我有一个 orders 表和一个 products 表以及一个 orders_products 表。

在订单模型中,我设置了 $hasAndBelongsToMany = 'Product';

orders_products 表中,我有几个额外的字段:order_idproduct_id 加上 pricequantity 以获取销售价格和销售数量。

我通过以下方式保存数据:

$this->Order->saveAll($data);

$data 是这样的:

Array
(
[Order] => Array
(
[user_email] => st@kr.com
[billing_first] => Steve
... //more excluded
[total] => 5000
)

[Product] => Array
(
[0] => Array
(
[id] => 1
[price] => 5000.00
[quantity] => 1
)

)

)

订单已保存到订单表中,但没有任何内容保存到 orders_products 表中。我希望 orders_products 表保存 [new_order_id], 1, 5000.00, 1

我确实收到了这条通知:

Notice (8): Undefined index: id [CORE/cake/libs/model/model.php, line 1391]

Model::__saveMulti() - CORE/cake/libs/model/model.php, line 1391
Model::save() - CORE/cake/libs/model/model.php, line 1355
Model::__save() - CORE/cake/libs/model/model.php, line 1778
Model::saveAll() - CORE/cake/libs/model/model.php, line 1673
CartsController::saveOrder() - APP/controllers/carts_controller.php, line 128
CartsController::checkout() - APP/controllers/carts_controller.php, line 172
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83

有什么想法吗?

最佳答案

HABTM 超卖。很多时候它不能满足需求,比如当你有额外的数据要存储时。你最好在模型之间建立 hasMany/belongsTo 关系。

摘自 CakePHP 书:

What to do when HABTM becomes complicated?

By default when saving a HasAndBelongsToMany relationship, Cake will delete all rows on the join table before saving new ones. For example if you have a Club that has 10 Children associated. You then update the Club with 2 children. The Club will only have 2 Children, not 12.

Also note that if you want to add more fields to the join (when it was created or meta information) this is possible with HABTM join tables, but it is important to understand that you have an easy option.

HasAndBelongsToMany between two models is in reality shorthand for three models associated through both a hasMany and a belongsTo association.

在你的情况下,我建议制作一个 LineItem 模型并以这种方式加入所有内容:

  • Order 有许多 LineItem
  • LineItem belongsTo Order, Product

关于php - 用额外的字段保存 HABTM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com