Laravel:保存/附加/同步自定义数据透视模型(belongsToMany)
Laravel: save / attach / sync custom pivot model (belongsToMany)
希望你今天过得愉快。
我正在使用 Laravel 8。我有三个模型,我需要这些模型“纠缠”,可以这么说。
所以,我有三个基本的 tables
areas,threats,positions
---
id
name
所以需要的关系是这样的:
- Every
t3
belongsToMany t1
反之亦然。 (多对多)
- 每个
t3.t1
关系 belongsToMany t2
(多对多)
到目前为止我的方法是这样的:
- 对于第一个关系,我在模型上定义了 belongsToMany 关系 (
t3.t1
)。
- 对于第二个关系,我为枢轴 table 创建了一个 custom pivot model,在该模型中我定义了第二个多对多关系 (
t3t1.t2
)。
到目前为止,第一个关系可以通过 $model->relatedModel()->attach($id);
.
来挽救
现在,对于第二个关系,如何附加相关模型?
我最后的办法是查询保存的自定义枢轴模型并附加 t2
个模型,但我想先问一下是否有清洁器,eloquent -laravel 方法。
任何建议都会有所帮助。预先感谢您抽出宝贵时间。
说明
attach
方法实际上是一个Model
函数。所以你的 withPivot
t3.t1
还不是模型
,当您使用 pivot magic method
从您的关系中访问时,您的关系属于许多 它仅 return 列
答案
所以对于您的情况,withPivot
t3.t1
转向 Model instance
。这里是步骤
- 创建扩展
use Illuminate\Database\Eloquent\Relations\Pivot;
的新 PivotModel
- 在您的
t1Model
上,将 using($classNamespace)
添加到 belongsToMany
方法,例如:belongsToMany()->using(PivotModel::class)
- 然后当
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 主元关系中使用额外的属性。
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);
我希望这会给你足够的想法来实现它。所有片段均来自文档,因此您可以直接搜索并参考
希望你今天过得愉快。
我正在使用 Laravel 8。我有三个模型,我需要这些模型“纠缠”,可以这么说。
所以,我有三个基本的 tables
areas,threats,positions
---
id
name
所以需要的关系是这样的:
- Every
t3
belongsToManyt1
反之亦然。 (多对多) - 每个
t3.t1
关系 belongsToManyt2
(多对多)
到目前为止我的方法是这样的:
- 对于第一个关系,我在模型上定义了 belongsToMany 关系 (
t3.t1
)。 - 对于第二个关系,我为枢轴 table 创建了一个 custom pivot model,在该模型中我定义了第二个多对多关系 (
t3t1.t2
)。
到目前为止,第一个关系可以通过 $model->relatedModel()->attach($id);
.
现在,对于第二个关系,如何附加相关模型?
我最后的办法是查询保存的自定义枢轴模型并附加 t2
个模型,但我想先问一下是否有清洁器,eloquent -laravel 方法。
任何建议都会有所帮助。预先感谢您抽出宝贵时间。
说明
attach
方法实际上是一个Model
函数。所以你的 withPivot
t3.t1
还不是模型
,当您使用 pivot magic method
从您的关系中访问时,您的关系属于许多 它仅 return 列
答案
所以对于您的情况,withPivot
t3.t1
转向 Model instance
。这里是步骤
- 创建扩展
use Illuminate\Database\Eloquent\Relations\Pivot;
的新 - 在您的
t1Model
上,将using($classNamespace)
添加到belongsToMany
方法,例如:belongsToMany()->using(PivotModel::class)
- 然后当
t1->getT2s->pivot
已经 returningModel instance
并且你可以使用attach
函数到那个 pivot
PivotModel
我能想到的是2种方式,一种只是参考Spatie Laravel Role permission
在 Spatie 中,关系就像 Many-to-many Permission and Role 和 Many-to-Many 之间的关系多态关系映射用户、角色和权限。
或
在 many-to-many 主元关系中使用额外的属性。
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);
我希望这会给你足够的想法来实现它。所有片段均来自文档,因此您可以直接搜索并参考