7 months ago

Attaching a Polymorphic Many-to-Many Relationship

Posted 7 months ago by xtremer360

I have a Match model and a MatchCompetitor model. The MatchCompetitor model is the associated model for the match_competitors table with fields match_id, competitor_type, competitor_id, and side_number. For the Match model, I have the following relationship defined. However, when I'm trying to save competitors it is not saving the match_id.

public function competitors()
    return $this->morphToMany(MatchCompetitor::class, 'competitor', 'match_competitors', null, 'competitor_id');
$matchObject->competitors()->attach($player1, ['side_number' => $sideNumber]);

I'm getting the dreaded Not Null constraint failed but it should be applying the match_id through the relationship.

For the SQL that gets saved shows up as such which is wrong because it should be App\Models\Player and should be able to fill in the match_id for that table.

#sql: "insert into "match_competitors" ("competitor_id", "competitor_type", "side_number") values (?, ?, ?)"
      #bindings: array:3 [
        0 => 1
        1 => "App\Models\Match"
        2 => 0

Please sign in or create an account to participate in this conversation.