samedi 11 février 2017

Laravel: How can I insert these relationships?

I am trying to log distance(s) to successful field goal attempts. My table field_goal_distances has 3 columns: athlete_id, game_id, distance

I am pretty sure it's my relationships I don't have set up correctly. Any suggestions are greatly appreciated!

Distance.php

/**
 * A distance belongs to a field goal.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function field_goal()
{
    return $this->belongsTo('App\FieldGoal', 'game_id', 'id');
}

FieldGoal.php

/**
 * A weekly field goal can have many distances.
 *
 */
public function distances()
{
    return $this->belongsToMany('App\Distance', 'id', 'game_id');
}

Here is how I am attempting to attach them in my controller:

 if ($field_goal->save()) {
        if ($request->distances) {  // an array of numbers [0] => 22, [1] => 45 etc.
            $game = FieldGoal::find($field_goal->id);

            $game->distances()->attach($request->distances);
        }

        return response()->json(['success' => $field_goal], 200);
    }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kFgdfE
via IFTTT

Aucun commentaire:

Enregistrer un commentaire