File tree Expand file tree Collapse file tree 3 files changed +55
-9
lines changed Expand file tree Collapse file tree 3 files changed +55
-9
lines changed Original file line number Diff line number Diff line change 1+ package gorm
2+
3+ import (
4+ godatabases "github.com/ralvarezdev/go-databases"
5+ "gorm.io/gorm"
6+ )
7+
8+ type (
9+ // Constraint struct
10+ Constraint struct {
11+ model interface {}
12+ field string
13+ }
14+ )
15+
16+ // NewConstraint creates a new constraint
17+ func NewConstraint (model interface {}, field string ) * Constraint {
18+ return & Constraint {
19+ model : model ,
20+ field : field ,
21+ }
22+ }
23+
24+ // CreateConstraint creates a new constraint
25+ func CreateConstraint (database * gorm.DB , constraint * Constraint ) error {
26+ // Check if the database or the constraint is nil
27+ if database == nil {
28+ return godatabases .ErrNilDatabase
29+ }
30+ if constraint == nil {
31+ return ErrNilConstraint
32+ }
33+
34+ // Create the constraint
35+ return database .Migrator ().CreateConstraint (
36+ constraint .model ,
37+ constraint .field ,
38+ )
39+ }
40+
41+ // CreateConstraints creates new constraints
42+ func CreateConstraints (database * gorm.DB , constraints []* Constraint ) error {
43+ for _ , constraint := range constraints {
44+ if err := CreateConstraint (database , constraint ); err != nil {
45+ return err
46+ }
47+ }
48+ return nil
49+ }
Original file line number Diff line number Diff line change 55)
66
77var (
8- ErrNilJoinField = errors .New ("join field cannot be nil" )
8+ ErrNilJoinField = errors .New ("join field cannot be nil" )
9+ ErrNilConstraint = errors .New ("constraint cannot be nil" )
910)
Original file line number Diff line number Diff line change @@ -27,7 +27,7 @@ func NewJoinField(
2727 }
2828}
2929
30- // SetupJoinTable setups the join table between two models
30+ // SetupJoinTable setups the join table
3131func SetupJoinTable (
3232 database * gorm.DB ,
3333 joinField * JoinField ,
@@ -47,17 +47,13 @@ func SetupJoinTable(
4747 )
4848}
4949
50- // SetupJoinTables setups the join tables between multiple models
50+ // SetupJoinTables setups the join tables
5151func SetupJoinTables (
5252 database * gorm.DB ,
5353 joinFields []* JoinField ,
54- ) error {
54+ ) ( err error ) {
5555 for _ , joinField := range joinFields {
56- err := SetupJoinTable (
57- database ,
58- joinField ,
59- )
60- if err != nil {
56+ if err = SetupJoinTable (database , joinField ); err != nil {
6157 return err
6258 }
6359 }
You can’t perform that action at this time.
0 commit comments