【问题标题】:CakePHP - Saving an hasMany through associationCakePHP - 通过关联保存 hasMany
【发布时间】:2013-05-23 05:50:55
【问题描述】:

我目前正试图弄清楚如何通过关系保存 hasMany。

我的桌子是:

卡片: id, name

颜色: id, name, color

card_colors(与模型 CardColor 关联): id, card_id, color_id, cost

hasMany 通过关联:

Card hasMany CardColor
Color hasMany CardColor
CardColor belongsTo Card
CardColor belongsTo Color

Card::beforeSave() 中,我将重构我的$data 变量,使其具有以下结构:

array(
'Card' => array(
    'name' => 'theCard',
    'CardColor' => array(
        array(
            'card_id' => 4,
            'color_id' => 5,
            'cost' => 2
        ),
        array(
            'card_id' => 5,
            'color_id' => 2,
            'cost' => 3
        )
    )
)
)

但是,我不知道如何获取我当前插入的卡的 card_id。有没有更Cake-y 的方式通过关联来保存 hasMany(例如在保存时以某种方式自动获取卡片 ID)?

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    试试这个:

    • 在模型中使用 $this->Card-create() // 或仅使用 $this->create()
    • 在 Card::beforeSave() 中,不要设置索引 CardColor[i][card_id]
    • 以这种方式保存:$this->saveAssociated($data)

    【讨论】:

    • 谢谢,除了我在 saveAll() 方法中使用 array('deep' => true) 而不是使用 saveAssociated($data) 之外,这一切都有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2014-03-06
    • 1970-01-01
    相关资源
    最近更新 更多