many-to-many polymorphic relations

蹲街弑〆低调 提交于 2019-11-30 21:17:41

问题


I need to create a polymorphic relationship between Entity2, Entity1 and Types. the relationship between event and Types is easy to do, but tou have a problem in the relationship between Entity2 and Types, because it is a many-to-many relation.

class CreateTypesTable extends Migration {
   public function up()
    {
        Schema::create('types', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('typeable_id');
            $table->string('typeable_type', 20);
            $table->string('name', 20);
            $table->text('description')->nullable();
        });
    }
}

class Entity1 extends Eloquent {
    public function type()
    {
        return $this->morphMany('App\Models\Type', 'typeable');
    }
}

class Type extends Eloquent {

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

as the relationship between types and Entitys2 is many to many, do not know how to create, because it takes a pivot table.

    class Entity2 extends Eloquent {
        public function types()
        {
//          return $this->morphMany('App\Models\Type', 'typeable');
        }
    }

回答1:


You need to use another polymorphic method for a many-to-many relationship: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L805 morhpToMany and belongsToMany where you pass the related model as a parameter.



来源:https://stackoverflow.com/questions/17198285/many-to-many-polymorphic-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!