簡體   English   中英

將具有相同ID但不同數據的多個記錄保存到聯接表中

[英]Saving multiple records to the join table with same ids but different data

我正在用cakephp3構建一個用於食品的電子商務應用程序,並且試圖使用不同的_joinData將同一product多個記錄同時保存到_joinDataorders_products中。

當我保存不具有相同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保存它們兩者?

使用“通過”選項。

<?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');
    }
}

然后像這樣保存訂單:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM