Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

datatypes.JSONQuery support empty keys #273

Open
leavest opened this issue Oct 15, 2024 · 0 comments
Open

datatypes.JSONQuery support empty keys #273

leavest opened this issue Oct 15, 2024 · 0 comments
Assignees

Comments

@leavest
Copy link

leavest commented Oct 15, 2024

Describe the feature

I want query json columns with sql SELECT * FROM `group` WHERE JSON_EXTRACT(`users`,'$') LIKE '%admin%'
But I use datatypes.JSONQuery("files").Likes("%"+user+"%") and get error
Because method not support empty key

if len(jsonQuery.keys) > 0 {

package main

import (
	"fmt"
	"strconv"
	"strings"

	"gorm.io/datatypes"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type Group struct {
	ID    uint                        `gorm:"primarykey"`
	Users datatypes.JSONSlice[string] `gorm:"type:json" `
	Name  string
}

func main() {

	dsn := "root:123456@tcp(localhost:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.New(
		mysql.Config{
			DSN:                       dsn,
			DefaultStringSize:         256,
			DisableDatetimePrecision:  true,
			DontSupportRenameIndex:    true,
			DontSupportRenameColumn:   true,
			SkipInitializeWithVersion: false,
		}),
	)
	if err != nil {
		panic(err)
	}

	var groups []Group

	user := "admin"

	db.Debug().
		// Where(datatypes.JSONQuery("users").Likes("%"+user+"%")). // want to support
		Where("JSON_EXTRACT(`users`,'$') LIKE ?", "%"+user+"%").  // current use
		Find(&groups)
}
<!-- Describe the requested Feature -->

## Motivation

<!-- Describe the motivation behind it -->

## Related Issues

<!-- Link related issues here -->

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants