Skip to content

Instantly share code, notes, and snippets.

@iamdtang
Last active February 5, 2019 08:29
Show Gist options
  • Save iamdtang/7808bf0f5170199dda48664035754241 to your computer and use it in GitHub Desktop.
Save iamdtang/7808bf0f5170199dda48664035754241 to your computer and use it in GitHub Desktop.
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