lundi 20 juin 2016

Inserting related models through nested relationships (Laravel)

Aye!

I do understand how and when to create or associate related models 1 level deep. But it is about 3 levels deep in this case and everyone loses their minds :)

How it works

User wants to play a match. Every match got exactly two teams with the same amount of players on each side. Matches will create new teams and new players, even if the users remain.

Main questions

  • how to make this work?
  • what does it need to be oop-beautiful?
  • ideas for database design?

What we have:

User players() hasMany(Player) < Player user() belongsTo(User) > Player team() belongsTo(Team) < Team players() hasMany(Player)
Team match() belongsTo(Match) < Match teams() hasMany(Team) > Match winner() belongsTo(Team, 'winner_id')

MatchController

public function store(Request $request)
{
    $this->validate($request, [
        'type' => 'required',
    ]);

    $user = $request->user();

    // TODO: create only if there's no open match
    $match = Match::create([
        'type' => $request->type,
    ]);

    $team = $match->teams()->associate($match);

    $player = $team->players()->create([
        'name' => $user->name,
    ]);

    // TODO: redirect to the stored match
    return redirect('/ranking');
}

I just ended up having nothing. What is the magic to save through the models?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire