Skip to content

Instantly share code, notes, and snippets.

@skaterdav85 skaterdav85/Genre.php
Last active Feb 5, 2019

Embed
What would you like to do?
Laravel Eloquent relationship examples based on http://www.sqlitetutorial.net/sqlite-sample-database/
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Genre extends Model
{
protected $primaryKey = 'GenreId';
public function tracks()
{
return $this->hasMany('App\Track', 'GenreId');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Playlist extends Model
{
protected $primaryKey = 'PlaylistId';
public function tracks()
{
return $this->belongsToMany('App\Track', 'playlist_track', 'PlaylistId', 'TrackId');
}
}
<?php
// all Metal tracks
Genre::find(3)->tracks;
// get the Metal genre from track 78 (Master of Puppets)
Track::find(78)->genre;
// Update a track's genre
Track::find(78)->genre()->associate(Genre::find(3));
// Many to Many relationships
// which playlists Master of Puppets is a part of
Track::find(78)->playlists;
// all tracks part of the Brazillian music playlist
Playlist::find(11)->tracks;
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Track extends Model
{
protected $primaryKey = 'TrackId';
public function genre()
{
return $this->belongsTo('App\Genre', 'GenreId');
}
public function playlists()
{
return $this->belongsToMany('App\Playlist', 'playlist_track', 'TrackId', 'PlaylistId');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.