CaldwellYSR
CaldwellYSR

Reputation: 3206

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('App\Characteristics');
}

app/Characteristics.php

public function character() {
    return $this->belongsTo('App\Character');
}

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($character->id);
    // 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?

Upvotes: 0

Views: 289

Answers (1)

Rahul M
Rahul M

Reputation: 1509

I think you need to save the character model first, because if you're building a hasMany/belongsTo relationship your characteristics table must have a column for character_id, and when you do $character->characteristics()->saveMany($characteristics); Laravel will try to insert the ID from the parent model. And as per the code shared by you, you've just instantiated the model, by this point of time it doesn't have an ID associated with it. So you need to save the character model first and assuming the getCharacteristics() method is returning an array/collection of Characteristics Models, Following should work:

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

And to further clarify this for you, from the characteristics method in your Character model an instance of HasMany not a Builder is being returned, thus saveMany works here.

Upvotes: 1

Related Questions