Will
Will

Reputation: 4705

Saving has_many records in SilverStripe

I have a DebatePage that has_many votes:

static $has_many = array(
    'Votes' => 'Vote'
);  

and a corresponding Vote DataObject

static $belongs_to = array(
    'DebatePage' => 'DebatePage'
);

When a user clicks "yes", I would like to save a vote for that page.

What is the syntax for that?

I'm looking to do something like this:

$this->dataRecord->Votes()->add($array('motion' => true));

How do I do this correctly?

Upvotes: 1

Views: 1696

Answers (3)

Mia
Mia

Reputation: 1

You can add the object to the has_many manually if needed, but it is already done automatically. If you use $object->ForreignID = $hasOneObject->ID, followed by $form->saveInto($object), it will automatically add the object to the has_many relationship.

Upvotes: 0

colymba
colymba

Reputation: 2644

similar to what @3dgoo wrote but with a different syntax, taking advantage of ::create():

$vote = Vote::create(array(
    'Motion' => true
));
$this->Votes()->add( $vote );

This implies that on your DebatePage the Vote relation is called Votes. $belongs_to still needs to be changed to a $has_one-relation.

Upvotes: 7

3dgoo
3dgoo

Reputation: 15794

Here is a function to create a new Vote in the database:

public function SubmitVote() {
    $vote = new Vote();
    $vote->DebatePageID = $this->ID;
    $vote->Motion = true;
    $vote->write();
}

Please note, your Vote DataObject should have a $has_one relationship back to DebatePage rather than $belongs_to:

static $has_one = array(
    'DebatePage' => 'DebatePage'
); 

Upvotes: 2

Related Questions