我有来自第 3 方服务调用的产品数据,然后我从中创建一个对象并将其保存到我的 MySQL 数据库。我的模型如下:
'产品' hasMany>> 'product_sku' hasMany>> 'product_sku_attributes'
表关系
在我的 ProductsTable.phpinitialize() 方法中,我有:
$this->hasMany('ProductSkus', [
'foreignKey' => 'product_no',
'dependent' => true,
]);
在我的 ProductSkusTable.phpinitialize() 方法中,我有:
$this->hasMany('ProductSkuAttributes', [
'foreignKey' => 'product_sku_id',
'bindingKey' => 'id',
'propertyName' => 'product_sku_attributes',
'dependent' => true,
]);
我的控制器:
$products = TableRegistry::get('Products');
$entity = $products->newEntity($product_data[0]);
$products->save($entity, [
'associated' => [
'ProductSkus',
'ProductSkus.ProductSkuAttributes',
]
]);
这是我的实体调试的相关片段:
'product_skus' => [
(int) 0 => object(App\Model\Entity\ProductSkus) {
'sku' => 'BDS1401H',
'sku_price' => (float) 366.76,
'sku_weight' => (float) 38.1,
'sku_img_main' => '',
'sku_img_large' => '',
'sku_img_default' => false,
'is_default' => true,
'product_sku_attributes' => [
(int) 0 => [
'product_no' => (int) 23200,
'sku' => 'BDS1401H',
'attribute_name' => 'Front Sway Bar Links',
'option_name' => 'Stock'
],
(int) 1 => [
'product_no' => (int) 23200,
'sku' => 'BDS1401H',
'attribute_name' => 'Shock Options',
'option_name' => 'NX2 Series'
],
(int) 2 => [
'product_no' => (int) 23200,
'sku' => 'BDS1401H',
'attribute_name' => 'Steering Stabilizer Options',
'option_name' => 'Stock'
]
],
'[new]' => true,
'[accessible]' => [
'*' => true,
'id' => true
],
'[dirty]' => [
'sku' => true,
'sku_price' => true,
'sku_weight' => true,
'sku_img_main' => true,
'sku_img_large' => true,
'sku_img_default' => true,
'is_default' => true,
'product_sku_attributes' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'ProductSkus'
},
(int) 1 => object(App\Model\Entity\ProductSkus) { ...
我仔细检查了一遍,所有字段都在表实体类中设置为可访问。另外,为了简单起见,此时我只想保存一个产品记录,因此是 $products->newEntity()。
我的数据保存到“products”和“product_skus”表没有问题,但保存到“product_sku_products”表没有问题。谁能看出问题是什么吗?是因为我没有使用相同的外键吗?
为了清楚起见,请让我知道我还能提供什么。