Last active
February 5, 2019 08:29
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Database\Eloquent\Model; | |
class Genre extends Model | |
{ | |
protected $primaryKey = 'GenreId'; | |
public function tracks() | |
{ | |
return $this->hasMany('App\Track', 'GenreId'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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