简体   繁体   中英

Reverse polymorphic relation in Laravel 5

Suppose we have following models: a Warrior , an Axe and a Sword

Is there a way to make the following behavior possible?

$warrior->weapon = $sword;
// ...

or

$warrior->weapon = $axe;
// ...

In other words, is it possible to treat separate models as if they had similar types with Eloquent ?

PS

Obviously, above is a simplified example of a problem only serving the purpose of conveying the gist of it.

Yes, you can make weapon a polymorphic relation . Add columns weapon_type and weapon_id to your table, which can be done in a migration file with the morphs type:

Schema::table('warriors', function ($table) {
    $table->morphs('weapon');
});

Now you are ready to add your relationship to the Warrior model:

public function weapon() {
    return $this->morphTo();
}

That's it! Now you can add the weapon and Eloquent will take care of the rest. The relation even supports eager loading. I suggest that all your weapons should implement an interface so you know what methods they have in common, but unfortunately there is no way for Eloquent to enforce that interface for you through the PHP type system.

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