【问题标题】:Is it possible to make many-to-many morphed relation on same model in Laravel? (Two morphed by relations are in the same Model)是否可以在 Laravel 中对同一模型进行多对多变形关系? (由关系变形的两个在同一个模型中)
【发布时间】:2019-09-06 21:22:27
【问题描述】:

我有带表格的 Role 和 DocType 模型。 DocTypes 必须由特定角色批准,并由另一个特定角色创建。 这是表结构:

Roles
id | name

DocTypes
id | name | author_id | approved

docTypes_roles_table
doc_type_id | role_id| role_type

这是我的代码:

在 AppServiceProvider 类中:

public function boot() {
 Schema::defaultStringLength(191);

 Relation::morphMap([
    'approve' => 'App\Models\Role',
    'create' => 'App\Models\Role',
 ]);
}

在角色类中

public function docTypes() {
    return $this->morphToMany('App\Models\DocType', 'role','doc_type_role');
    }

在 DocType 类中

/**
     * Get the polymorphic relation with roles table
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function roles() {
        return $this->morphedByMany('App\Models\Role', 'role','doc_type_role')->withPivot('role_type');
    }

    /**
     * Get roles which must approve the docType
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function approveRoles() {
        return $this->roles()->wherePivot('role_type','approve')->withPivot('sequence')->orderBy('sequence');
    }

    /**
     * Get roles which create the docType
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function createRoles() {
        return $this->roles()->wherePivot('role_type','create');
    }

但是当我将角色附加到createRoles() 时,它会保存到数据库“批准”类型。

$trip = User::find(1)->docTypes()->create([
    "name"         => "business_trip",
    "display_name" => "Business Trip",
]);
$trip->approveRoles()->sync([
    2 => ['sequence' => 1],
]);

$trip->createRoles()->attach([5,3]);

【问题讨论】:

    标签: php laravel many-to-many relation polymorphic-relationship


    【解决方案1】:

    我通过将 Role 类扩展到另一个 CreatorRole 类来做到这一点。 但是现在如果我需要这样的东西,我会在数据透视表中添加另一列(例如“类型”)并通过这个数据透视值进行附加。

    【讨论】:

      猜你喜欢
      • 2016-02-21
      • 2016-07-12
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多