【发布时间】: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,我尝试了以下方法:
$project->owners()->sync([2,3]
| user_id | userable_id | userable_type | usership |
|---------|-------------|--------------------|-------------|
| 2 | 55 | App\Models\Project | Owner |
| 10 | 55 | App\Models\Project | Owner |
(将“所有者”分配为“用户身份”,似乎是第一个/默认值)
$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 |
显然,这两者都会影响同一个项目上的所有者关系,这是不理想的。
我也尝试过手动分离和附加。但是再次忽略了关系属性“用户”。下面都删除了示例中的所有五行,所以在我进入附件之前功能失败......
$project->contributors()->detach();$project->contributors()->detach()->where('usership', 'Contributor');
非常感谢任何帮助!
【问题讨论】:
标签: laravel eloquent synchronization polymorphism pivot