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

标签 php mysql cakephp cakephp-1.3

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

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

我有一个 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/5795615/

相关文章:

php - 如何收集两个不同查询的 COUNT(*) ?

mysql - 比较 mysql 中的日期是否需要格式化

php - Cakephp 2.x自定义异常渲染

php - mysql 获取数组错误?

javascript - 如何在页面加载时自动调用按钮提交

python - 带池的 SQLAlchemy 不关闭数据库连接

CakePHP 3 - beforeSave 回调在编辑时不起作用

symfony - TYPO3 Composer 依赖冲突

php - 如何从 Simplepie(多个)提要中删除重复的帖子

php - Laravel 5.1 登录文件权限