user1927371
user1927371

Reputation:

CakePHP - Saving an hasMany through association

I'm currently trying to figure out how to save a hasMany through relationship.

My tables are:

cards: id, name

colors: id, name, color

card_colors (associated with the model CardColor): id, card_id, color_id, cost

hasMany through Association:

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

In Card::beforeSave(), I'm going to reconstruct my $data variable so that it has this structure:

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
        )
    )
)
)

However, I don't know how to get the card_id for the card that I am currently inserting. Is there a more Cake-y way of saving a hasMany through association (such as getting the card id automatically in some way while saving)?

Upvotes: 2

Views: 1893

Answers (1)

Claudio Bredfeldt
Claudio Bredfeldt

Reputation: 1422

Try this:

  • Use $this->Card-create() // or just $this->create() in the model
  • In Card::beforeSave(), don't set the index CardColor[i][card_id]
  • Do the save this way: $this->saveAssociated($data)

Upvotes: 1

Related Questions