Laravel inserting into a three-way pivot table Laravel inserting into a three-way pivot table database database

Laravel inserting into a three-way pivot table


Well:

$tag = Tag::firstOrCreate(array('text' => $tag_text));TagTrackUser::create(array(    "tag_mdbid" => $tag->mdbid,    "track_mdbid" => $track->mdbid,    "user_mdbid" => Auth::user()->mdbid));

Something like that? firstOrCreate does what the name says it does, the rest is pretty straightforward Eloquent.


Since seems that there is not an appropriate pattern in Laravel, the cleaner and easier way is to implement any three-pivot-relationships via a model dedicated to the pivot table:

class Trackpublic function trackTags(){    return $this->hasMany('TagTrack');}...class Tagpublic function tagTracks(){    return $this->hasMany('TagTrack');}...class TagTrackpublic function track(){    return $this->belongsTo('Track');}public function tag(){    return $this->belongsTo('Tag');}public function anotherRelationship(){...}

You can do:

$track->trackTags->myCustomPivotDataAndRelationship()

and in TagTrack you have freedom to add as many relationship and field I want

Note than you can still keep the many to many to use when you don't need to access pivot relationships