Laravel:保存/附加/同步自定义数据透视模型(belongsToMany)

Laravel: save / attach / sync custom pivot model (belongsToMany)

希望你今天过得愉快。

我正在使用 Laravel 8。我有三个模型,我需要这些模型“纠缠”,可以这么说。

所以,我有三个基本的 tables

areas,threats,positions
---
id
name

所以需要的关系是这样的:

到目前为止我的方法是这样的:

到目前为止,第一个关系可以通过 $model->relatedModel()->attach($id);.

来挽救

现在,对于第二个关系,如何附加相关模型?

我最后的办法是查询保存的自定义枢轴模型并附加 t2 个模型,但我想先问一下是否有清洁器,eloquent -laravel 方法。

任何建议都会有所帮助。预先感谢您抽出宝贵时间。

说明

attach方法实际上是一个Model函数。所以你的 withPivot t3.t1 还不是模型 ,当您使用 pivot magic method 从您的关系中访问时,您的关系属于许多 它仅 return 列

答案

所以对于您的情况,withPivot t3.t1 转向 Model instance。这里是步骤

  1. 创建扩展 use Illuminate\Database\Eloquent\Relations\Pivot;
  2. 的新 PivotModel
  3. 在您的 t1Model 上,将 using($classNamespace) 添加到 belongsToMany 方法,例如:belongsToMany()->using(PivotModel::class)
  4. 然后当 t1->getT2s->pivot 已经 returning Model instance 并且你可以使用 attach 函数到那个 pivot

我能想到的是2种方式,一种只是参考Spatie Laravel Role permission

在 Spatie 中,关系就像 Many-to-many Permission and Role 和 Many-to-Many 之间的关系多态关系映射用户、角色和权限。

在 many-to-many 主元关系中使用额外的属性。

somethinglike

return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

并且附加和分离也接受 extra attributes

$user->roles()->attach($roleId, ['expires' => $expires]);

检索时您可以使用 where 子句来指定您的选择

return $this->belongsToMany('App\Role')->wherePivot('approved', 1);

我希望这会给你足够的想法来实现它。所有片段均来自文档,因此您可以直接搜索并参考