samedi 23 juillet 2016

Laravel insert relationship in newly created model

I have a relationship set up between two models. The two models are set up like:

app/Character.php

public function characteristics() {
    return $this->hasMany('AppCharacteristics');
}

app/Characteristics.php

public function character() {
    return $this->belongsTo('AppCharacter');
}

then in a controller I have a method to create a new character with a predetermined set of characteristics as follows:

app/Http/Controllers/CharacterController.php

public function newCharacter(Request $request) {
    $character = new Character();
    $characteristics = getCharacteristics();
    // Save basic character stuff
    $character->characteristics()->saveMany($characteristics);
    $character->save();
}

The highlighted line is throwing an error because saveMany is not a function of Builder so how can I get the created character without having to do a find that would have to hit the database again?

Aucun commentaire:

Enregistrer un commentaire