多对多关系 [英] many-to-many polymorphic relations

查看:127
本文介绍了多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Entity2,Entity1和Types之间创建一个多态关系。
事件和类型之间的关系很容易做到,但是在Entity2和Types之间的关系中有一个问题,因为它是一个多对多关系。

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

作为类型和Entitys2之间的关系是很多到很多,不知道如何创建,因为它需要一个数据透视表。

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


推荐答案

你需要为多对多关系使用另一种多态方法: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L805 morhpToMany belongsToMany 将相关模型作为参数传递。

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.

这篇关于多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆