Miguel Borges
Miguel Borges

Reputation: 7659

many-to-many polymorphic relations

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.

enter image description here

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');
        }
    }

Upvotes: 0

Views: 1210

Answers (1)

marcanuy
marcanuy

Reputation: 23962

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.

Upvotes: 1

Related Questions