使用相同的ID但不同的数据将多个记录保存到连接表

时间:2016-06-06 15:29:15

标签: php cakephp cakephp-3.0

我正在cakephp3中为食物构建一个电子商务应用,并且我正在尝试将同一product的多个记录同时保存到联接表orders_products_joinData

当我保存多个没有相同ID的产品时,它按预期工作,但是当我有两个具有相同ID的产品时,它没有。例如,当我尝试订购一份带法式酱料的凯撒沙拉和一份带酸奶酱的凯撒沙拉时,我需要保存两份记录:

[
    'products' => [
        (int) 0 => [
            'id' => (int) 35,
            '_joinData' => [
                'prodcut_variation' => 'yogurt dressing',
                'product_name' => 'ceasar salad',
                'product_net_price' => (float) 1.5,
                'product_qty' => (int) 26,
                'tax_id' => (int) 2
            ]
        ],
        (int) 2 => [
            'id' => (int) 35,
            '_joinData' => [
                'prodcut_variation' => 'french dressing',
                'product_name' => 'ceasar salad',
                'product_net_price' => (float) 1.5,
                'product_qty' => (int) 10,
                'tax_id' => (int) 2
            ]
        ],
    ],
]

但是cakephp只能保存第一个。我如何告诉cakephp保存它们?

1 个答案:

答案 0 :(得分:0)

Use the 'through' Option.

session['file']

然后像这样保存订单:

<?php

class OrdersTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Products', [
            'through' => 'OrdersProducts',
        ]);
        $this->hasMany('OrdersProducts');
    }
}

class ProductsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Orders', [
            'through' => 'OrdersProducts',
        ]);
    }
}

class OrdersProductsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Orders');
        $this->belongsTo('Products');
    }
}