简体   繁体   中英

How to establish polymorphic relations with Eloquent

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

图示

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM