Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
感觉被束缚:在gorm中使用连接_Orm_Go Gorm - Fatal编程技术网

感觉被束缚:在gorm中使用连接

感觉被束缚:在gorm中使用连接,orm,go-gorm,Orm,Go Gorm,免责声明:这是我第一次使用ORM,我的SQL可能有点生疏 我有一个包含用户和歌曲的应用程序,我想计算并显示给定用户播放每首歌曲的次数。我知道如何使用SQL,但我无法将其转换为GORM。事情是这样的: package main import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) type User struct { ID int `gorm:"prima

免责声明:这是我第一次使用ORM,我的SQL可能有点生疏

我有一个包含用户和歌曲的应用程序,我想计算并显示给定用户播放每首歌曲的次数。我知道如何使用SQL,但我无法将其转换为GORM。事情是这样的:

package main

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type User struct {
    ID       int `gorm:"primary_key"`
    Listened []Listen
}

type Song struct {
    ID       int `gorm:"primary_key"`
    Title    string
    Listened []Listen
}

type Listen struct {
    UserID int `gorm:"primary_key;auto_increment:false"`
    SongID int `gorm:"primary_key;auto_increment:false"`
    Count  int
}
然后,让我们添加一些数据

func main() {
    db, err := gorm.Open("sqlite3", "test.db")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    db.DropTableIfExists(&User{}, &Song{}, &Listen{})
    db.CreateTable(&User{}, &Song{}, &Listen{})

    db.Save(&User{ID: 1})
    db.Save(&User{ID: 2})

    db.Save(&Song{ID: 1, Title: "oh yeah"})
    db.Save(&Song{ID: 2, Title: "greatest song"})
    db.Save(&Song{ID: 3, Title: "bestest song"})

    db.Save(&Listen{UserID: 1, SongID: 1, Count: 7})
    db.Save(&Listen{UserID: 1, SongID: 2, Count: 23})
    db.Save(&Listen{UserID: 2, SongID: 2, Count: 13})
    db.Save(&Listen{UserID: 2, SongID: 3, Count: 10})

    // do something here
}
现在,正如我所说,我想列出一个用户播放数据库中每首歌曲的次数。我搔了搔头之后,得出了这样的结论:

sqlite> select songs.id, l.count from songs
   ...> left join (select song_id, count from listens where user_id = 1) as l
   ...> on songs.id = l.song_id;
id          count     
----------  ----------
1           7         
2           23        
3

。。。我在这里。我只是不明白如何用GORM方法链来表达。或者我应该放弃并运行原始sql查询吗?

最后我找到了方法:

db.Tablesongs。 选择songs.id,listens.count。 Joinsleft join select*from侦听,其中user_id=?as listens on songs.id=listens.song_id,1。 查找和检索

此查询可能也适用。我希望这会有帮助

if err := db.Table("listens").Select("songs.id, listens.count").
Joins("JOIN songs on listens.song_id = songs.id").Where("user_id = ?", 
1).Find(&rs).Error; err != nil {
    fmt.Prinln(err)
}