【问题标题】:Laravel Polymorphic ManyToMany with Pivot - SyncLaravel 多态多对多与 Pivot - 同步
【发布时间】:2021-01-13 08:01:47
【问题描述】:

我想使用“userables”表来存储用户与其他各种模型的关系,例如“Projects”和“Actions”。用户关系还有一个属性,比如“Owner”或者“Contributor”。

尽管尝试了各种类似的帖子并仔细检查了 Laravel 文档,但我在同步(和/或附加和分离)与此附加属性的关系时遇到了问题。

作为预期功能的整体示例,给定用户 1 可以是项目 55 的所有者,以及项目 66 的所有者和贡献者。(用户也可能与各种操作有类似的关系。)

可用的向上迁移如下所示:

public function up()
    {
        Schema::create('userables', function (Blueprint $table) {
            $table->foreignId('user_id');
            $table->integer('userable_id');
            $table->string('userable_type');
            $table->enum('usership', ['Owner', 'Contributor']);
        });
    }

以 Projects 模型为例:

 public function contributors()
    {
        return $this->morphToMany('App\Models\User', 'userable')->where('usership', 'Contributor');
    }

    public function owners()
    {
        return $this->morphToMany('App\Models\User', 'userable')->where('usership', 'Owner');
    }

这一切都有效,我可以构建表单以从同一个表中提取数据,从而区分各种项目和/或操作的所有者和贡献者。我的问题是,当我尝试使用 sync() 进行更新时,Laravel 不会区分附加属性,即它将给定项目的所有者和贡献者视为同一事物。

示例: 项目 55 可能有两个所有者,ID 1 和 2,以及三个贡献者,ID 1、10 和 11。“Userables”看起来像:

| user_id | userable_id | userable_type      | usership    |
|---------|-------------|--------------------|-------------|
| 1       | 55          | App\Models\Project | Owner       |
| 2       | 55          | App\Models\Project | Owner       |
| 1       | 55          | App\Models\Project | Contributor |
| 10      | 55          | App\Models\Project | Contributor |
| 11      | 55          | App\Models\Project | Contributor |

要将 Project 55 的贡献者更新为用户 2 和 10,我尝试了以下方法:

  1. $project->owners()->sync([2,3]
| user_id | userable_id | userable_type      | usership    |
|---------|-------------|--------------------|-------------|
| 2       | 55          | App\Models\Project | Owner       |
| 10      | 55          | App\Models\Project | Owner       |

(将“所有者”分配为“用户身份”,似乎是第一个/默认值)

  1. $project->owners()->sync(2 => ['usership' => 'Contributor'], 3 => ['usership' => 'Contributor']);
| user_id | userable_id | userable_type      | usership    |
|---------|-------------|--------------------|-------------|
| 2       | 55          | App\Models\Project | Contributor |
| 10      | 55          | App\Models\Project | Contributor |

显然,这两者都会影响同一个项目上的所有者关系,这是不理想的。

我也尝试过手动分离和附加。但是再次忽略了关系属性“用户”。下面都删除了示例中的所有五行,所以在我进入附件之前功能失败......

  1. $project->contributors()->detach();
  2. $project->contributors()->detach()->where('usership', 'Contributor');

非常感谢任何帮助!

【问题讨论】:

    标签: laravel eloquent synchronization polymorphism pivot


    【解决方案1】:

    如果有人遇到这个问题并正在寻找类似的解决方案,我在多次搜索中发现了这篇文章:Laravel Attach/Detach model from pivot depending on pivot extra field

    我通过上面的 (4) 进行了调整,以使用 wherePivot 而不是 where(回想起来很有意义),现在一切正常。

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 1970-01-01
      • 2015-12-23
      • 2021-11-29
      • 2015-02-14
      • 2021-07-22
      • 2021-12-21
      • 2021-10-02
      • 1970-01-01
      相关资源
      最近更新 更多