如何使用gorm从数据库中删除项目范围

每次我运行 gorm 查询以从表中删除一系列行时,我都会收到以下错误。


(/home/gregf/code/go/src/github.com/gregf/gormtest/main.go:39)

[2015-06-24 18:55:56]  [0.34ms]  SELECT  id FROM "podcasts"


(/home/gregf/code/go/src/github.com/gregf/gormtest/main.go:50)

[2015-06-24 18:55:56]  near "LIMIT": syntax error


(/home/gregf/code/go/src/github.com/gregf/gormtest/main.go:50)

[2015-06-24 18:55:56]  [0.82ms]  DELETE FROM "episodes"  WHERE (podcast_id = '1') LIMIT 4 OFFSET 2

2015/06/24 18:55:56 &{{0 0   false } near "LIMIT": syntax error 0 <nil> 0xc20802c280 0xc20802c140 0xc20802f900 2 <nil> <nil> false  map[gorm:started_transaction0xc2080380c00xc20805a1c0:true] map[]}

在sqlite3中直接运行查询返回就好了


DELETE FROM "episodes"  WHERE (podcast_id = '1') LIMIT 4 OFFSET 2;

Run Time: real 0.000 user 0.000000 sys 0.000000

示例代码


package main


import (

    "log"


    "github.com/jinzhu/gorm"

    _ "github.com/mattn/go-sqlite3"

)


type Podcast struct {

    Id       int

    Title    string

    RssUrl   string `sql:"unique_index"`

    Episodes []Episode

}


type Episode struct {

    Id         int

    PodcastID  int

    Title      string

    Url        string `sql:"unique_index"`

    Downloaded bool

    Guid       string `sql:"unique_index"`

}


func main() {

    db, err := gorm.Open("sqlite3", "cache.db")

    if err != nil {

        log.Fatal(err)

    }

    db.LogMode(true)


    db.CreateTable(&Podcast{})

    db.CreateTable(&Episode{})


    rows, err := db.Table("podcasts").Select("id").Rows()

    if err != nil {

        log.Fatal(err)

    }


    for rows.Next() {

        var podcastId int

        rows.Scan(&podcastId)

        err := db.Table("episodes").Where("podcast_id = ?", podcastId).

            Limit(4).

            Offset(2).

            Delete(Episode{})


        if err != nil {

            log.Printf("%s\n", err)

        }

    }

}


慕容708150
浏览 147回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go