0
votes

Using Laravel and Eloquent. I have a database that looks like this:

Graphical Representation

The dance_performers.dance_perfomer_type field hosts values such as '\App\Dancer', '\App\Couple' or '\App\Formation'.

How would you proceed to connect the dance_performers.dance_perfomer_id to the different models? I am not sure how I am supposed to write the relationships in the different models. Should I create a \App\Performer model which would then direct to one of the three previously mentioned?

Using polymorphic relations:

class Dance extends Model {
    public function couples() {
        return $this->morphedByMany('\App\Couple', 'dance_performer');
    }
}

class Couple extends Model
{   
    public function dances() {
        return $this->morphToMany('App\Dance', 'dance_performer');
    }
}

Currently, $dances = \App\Dance::with('couples')->get(); only returns empty relations. I would appreciate the help.

2
check my answer it will solve you problem - Senthurkumaran

2 Answers

0
votes

According to your code everything is correct. I guess you don't have data in correct way in database. Add some data like below and check.

dances

id - 1, name - 'Dance A'

id - 2, name - 'Dance B'

couples

id - 1, name - 'Couple A'

id - 2, name - 'Couple B'

dance_performers

id - 1, dance_id - 1, dance_performer_type - '\App\Couple', dance_performer_id - 1

id - 2, dance_id - 2, dance_performer_type - '\App\Couple', dance_performer_id - 2

0
votes

Solved it. The type field should be App\ModelName and not \App\ModelName.