go-gorm / playground

GORM Playground (Please Create PR for this project to report issues)
MIT License
91 stars 697 forks source link

Question about Statement.table #771

Closed YuzuWiki closed 2 weeks ago

YuzuWiki commented 2 weeks ago

GORM Playground Link

https://github.com/go-gorm/playground/pull/1

Description

this issue about Statement.table . in some cases, it can lead to unexpected results.

Other issuse See: https://github.com/go-gorm/gorm/issues/7280

Source Code SEE: LINE 493, https://github.com/go-gorm/gorm/blob/master/statement.go

Example:

use SQL

type OtherTable struct { Name string }

var retSQL OtherTable db.Raw(SELECT name FROM xxx JOIN ..... LIMIT 1;).Scan(&retSQL )


some time, db.statement.table  will  be set to **other_table**.  now, db looks like this

db: { Statement: { Table: "other_table", Model: nil, ........ } }

now,If we continue to execute 

type User struct { ...... }

func (u User ) TableName() string { return "user" }

var u User db.Model(User{}).Where("id =?", uid).Find(&u)


maybe, we will get the following results
SELECT * FROM `database`.other_table WHERE id = ? limit 1;

but our expected result is
SELECT * FROM `database`.user WHERE id = ?;


<!-- Your use case -->