简体   繁体   English

Laravel 5中的反向多态关系

[英]Reverse polymorphic relation in Laravel 5

Suppose we have following models: a Warrior , an Axe and a Sword 假设我们有以下模型: WarriorAxeSword

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 ? 换句话说, 是否可以将单独的模型视为与Eloquent具有相似类型

PS 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 . 是的,您可以使weapon成为多态关系 Add columns weapon_type and weapon_id to your table, which can be done in a migration file with the morphs type: 在表中添加weapon_typeweapon_id列,可以在具有morphs类型的迁移文件中完成:

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

Now you are ready to add your relationship to the Warrior model: 现在您可以将您的关系添加到Warrior模型中:

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

That's it! 而已! Now you can add the weapon and Eloquent will take care of the rest. 现在,您可以添加武器,而Eloquent将负责其余的工作。 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. 我建议您所有的武器都应实现一个接口,以便您了解它们共有的方法,但是不幸的是,Eloquent无法通过PHP类型系统为您实施该接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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