I have 3 models: Song, SongArtist, Artist.
Relation between Song and Artist is many-to-many by SongArtist table. A song has many artists sing it, and order by field 'order' in table 'SongArtist'. I want when getting a song, the related artists object will be orderd by 'order' like this:
$song = Song::findFirstById(999);
$artists = $song->artists; [which already orderd]
Is there a way that do automatically or use built in function of Model? I have a solution that solve this problem but take more steps:
$song_id = 999;
$song = Song::findFirstById($song_id);
$songArtists = $song->getsongArtists(array(
"song_id = $song_id"
"order" => "order asc"
));
$artists = array();
foreach($songArtists as $songArtist) {
$artist_id = $songArtist->artist_id;
$artist = Artist::findFirstById($artist_id);
$artists[] = $artist;
}
return $artists;
Song:
public $id;
public function initialize()
{
$this->hasManyToMany(
"id",
"Bcdcnt\Models\SongArtist",
"song_id",
"artist_id",
"Bcdcnt\Models\Artist",
"id",
array('alias' => 'artists')
);
$this->hasMany("id", "Bcdcnt\Models\SongArtist", "song_id", array(
'alias' => 'songArtists',
'foreignKey' => array(
'action' => Relation::ACTION_CASCADE
)
));
}
SongArtist:
public $id;
public $song_id;
public $artist_id;
public $order;
Artist:
public $id;
$this->hasManyToMany(
"id",
"Bcdcnt\Models\SongArtist",
"artist_id",
"song_id",
"Bcdcnt\Models\Song",
"id",
array('alias' => 'songs')
);
$this->hasMany("id", "Bcdcnt\Models\SongArtist", "artist_id", array(
'alias' => 'songArtists',
'foreignKey' => array(
'action' => Relation::ACTION_CASCADE
)
));