I am building a music discovery service. My question is: How do I insert data into the three-way pivot table Tag_Track_User ?
I have this schema seen here at LaravelSD
It comprises of six main tables (and a few others): Artists, Albums, Tracks, Tags, Users and Tag_Track_User
The Artists->Albums->Tracks relationship is straightforward and as you'd expect.
Tags, Tracks and Users all relate to one-another as no two can exist without the third.
Artists hasMany() Albums
Albums hasMany() Tracks and belongsTo() an Artist
Tracks belongsTo() Albums
Tracks belongsToMany() Tags and belongsToMany() an Users
Tags belongsToMany() Tracks and belongsToMany() an Users
Users belongsToMany() Tags and belongsToMany() an Tracks
User model
public function tags()
{
return $this->belongsToMany('Tag', 'tag_track_user', 'user_mdbid', 'tag_mdbid')->withPivot('track_mdbid');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tracks()
{
return $this->belongsToMany('Track', 'tag_track_user', 'user_mdbid', 'track_mdbid')->withPivot('tag_mdbid');
}
The Tag and Track model contain the same respective relationships.
So my question is:
How do I insert data into the Tag_Track_User table? The tag_track_user table is a 3-way pivot table cointaining information about tracks that users have tagged.
You have to be logged in to tag a track (which means I have access to the user’s ID). The tracks ID is accessed as I am displaying it on the page where the form is contained. The tag on the other hand; if it already exists in the tags table, I want to get it’s ID and re-use that (as they are unique), if not, I want to create it, assign it an ID and insert that into the tag_track_user_table.
Any help I receive on this, is greatly appreciated.
How can I insert values to pivot table with Laravel best practices? $roles = Input::get('roles'); // arrays of role ids $user = new User(); $user->username = Input::get('username'); $user->password = Hash::make(Input::get('password')); $user->save();
To create a pivot table we can create a simple migration with artisan make:migration or use Jeffrey Way's package Laravel 5 Generators Extended where we have a command artisan make:migration:pivot.
Creating The Pivot Table's Migration The migration should look like this, it establishes the proper columns and foreign key relations to both the users and roles table. The migration will also set both user_id and role_id as the primary keys so there cannot be duplicates with both the same user_id and role_id .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With