【问题标题】:Insert to multiple tables in CakePHP在 CakePHP 中插入多个表
【发布时间】:2013-11-19 03:23:39
【问题描述】:

我是 CakePHP 的新手。现在我正在努力解决过去一个小时在互联网上找不到答案的问题。我正在尝试将以下数组保存到我的数据库中:

array(
    'Product' => array(
        'product_id' => '77adfe7754esda71r1999431',
        'supplier_id' => 'zalando_it',
        'product_name' => 'Sweater',
        'price_new' => '68.97',
        'affiliate_url' => 'http://example.com'
    ),
    'Image' => array(
        'image' => '99988_DP.jpg'
    )
)

现在这是我的 ERD 的一个示例:https://www.dropbox.com/s/1zvfqfxes53gibb/example.png

我在模型中正确连接了表(通过使用 belongsTo 和 hasMany 变量),但我仍然认为我做错了什么......原因当我使用函数时 $this->Supplier->模型“Feed”中的 saveAssociated($data) 不保存任何内容。 当我使用 $this->Supplier->Product->saveAssociated($data) 时,它会保存产品并使用 product_id 在 Image 表中创建记录,但将“image”字段留空。

只有当我使用 $this->Supplier->Product->Image->saveAssociated($data) 时,它才能正确保存所有内容。但这不是错的吗?因为在我看来,通过每个模型($this->Supplier->Product->Image...)来保存所有表格似乎并不正确......还是我错了?

【问题讨论】:

  • 你试过 $this->Supplier->saveAssociated($data, array('deep' => true));

标签: php mysql cakephp


【解决方案1】:

假设产品有很多图片,你的数据需要是这样的(注意“图片”是编号的,所以可以有多个):

array(
    'Product' => array(
        'product_id' => '77adfe7754esda71r1999431',
        'supplier_id' => 'zalando_it',
        'product_name' => 'Sweater',
        'price_new' => '68.97',
        'affiliate_url' => 'http://example.com'
    ),
    'Image' => array(
        0 => array(
            'image' => '99988_DP.jpg'
        )
    )
)

【讨论】:

  • 谢谢!那成功了。不幸的是,我无法使用 $this->Supplier->saveAll($data),但 $this->Supplier->Product->saveAll($data) 可以。至少我不必再调用函数中的每个模型了:)
  • 正确 - 如果您只是在供应商上运行保存,它不会保存,因为没有供应商数据要保存。很高兴它有帮助!
猜你喜欢
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 2010-10-31
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多