feat: add user_tenant associations

This commit is contained in:
2025-12-16 14:14:58 +08:00
parent d058b7ffda
commit 4722eef72c
9 changed files with 391 additions and 24 deletions

View File

@@ -2,6 +2,7 @@ package super
import (
"database/sql"
"quyun/v2/providers/app"
"go.ipao.vip/atom"

View File

@@ -16,7 +16,7 @@ type user struct{}
func (t *user) FindByID(ctx context.Context, userID int64) (*models.User, error) {
tbl, query := models.UserQuery.QueryContext(ctx)
model, err := query.Where(tbl.ID.Eq(userID)).First()
model, err := query.Preload(tbl.OwnedTenant, tbl.Tenants).Where(tbl.ID.Eq(userID)).First()
if err != nil {
return nil, errors.Wrapf(err, "FindByID failed, %d", userID)
}

View File

@@ -9,6 +9,7 @@ import (
"quyun/v2/database"
"quyun/v2/database/models"
"quyun/v2/pkg/consts"
"quyun/v2/pkg/utils"
"github.com/samber/lo"
. "github.com/smartystreets/goconvey/convey"
@@ -200,3 +201,62 @@ func (t *UserTestSuite) Test_Page() {
})
})
}
func (t *UserTestSuite) Test_Relations() {
Convey("test page", t.T(), func() {
// database.Truncate(
// t.T().Context(),
// t.DB,
// models.TableNameUser,
// models.TableNameTenant,
// models.TableNameTenantUser,
// )
// username := "test-user"
// mUser01 := &models.User{
// Username: username,
// Password: "test-password",
// Roles: types.NewArray([]consts.Role{consts.RoleUser}),
// Status: consts.UserStatusPendingVerify,
// }
// err := mUser01.Create(t.T().Context())
// So(err, ShouldBeNil)
// tenantModel := &models.Tenant{
// UserID: 1,
// Code: "abc",
// UUID: types.NewUUIDv4(),
// Name: "T01",
// Status: consts.TenantStatusVerified,
// }
// err = tenantModel.Create(t.T().Context())
// So(err, ShouldBeNil)
// count := 10
// for i := 0; i < count; i++ {
// mUser := &models.User{
// Username: fmt.Sprintf("user_%d", i),
// Password: "test-password",
// Roles: types.NewArray([]consts.Role{consts.RoleUser}),
// Status: consts.UserStatusPendingVerify,
// }
// err = mUser.Create(t.T().Context())
// So(err, ShouldBeNil)
// // create tenant user
// err = Tenant.AddUser(t.T().Context(), 1, mUser.ID)
// So(err, ShouldBeNil)
// }
Convey("filter tenant users", func() {
m, err := User.FindByID(t.T().Context(), 1)
So(err, ShouldBeNil)
// So(m.OwnedTenant, ShouldNotBeNil)
// So(m.Tenants, ShouldHaveLength, 10)
t.T().Logf("%s", utils.MustJsonString(m))
})
})
}