dsyua2828 2018-11-06 13:42
浏览 168

使用GORM时如何由当前上下文用户获取数据

I have the following relationship:

package models

import (
    "github.com/jinzhu/gorm"
)

type User struct {
    gorm.Model
    Site      Site
}


type Site struct {
    gorm.Model
    UserID    string
    Pageviews []Pageview
}

type Pageview struct {
    gorm.Model
    Site         Site
    SiteID       string
    Hostname     string `gorm:"not null"`
    Pathname     string `gorm:"not null"`
    IsNewVisitor bool   `gorm:"not null"`
    IsNewSession bool   `gorm:"not null"`
    IsUnique     bool   `gorm:"not null"`
    IsBounce     bool   `gorm:"not null"`
    IsFinished   bool   `gorm:"not null"`
    Referrer     string `gorm:"not null"`
    Duration     int64  `gorm:"not null"`
}

And typically, in a framework like Rails, the queries that you do are limited to the user context. For example:

GET /pageviews -> return all page views from the current user.

The same is true for Fathom, e.g:

func (api *API) GetSiteStatsPageviewsHandler(w http.ResponseWriter, r *http.Request) error {
    params := GetRequestParams(r)
    result, err := api.database.GetTotalSiteViews(params.SiteID, params.StartDate, params.EndDate)
    if err != nil {
        return err
    }
    return respond(w, http.StatusOK, envelope{Data: result})
}

Code in here.

Now: How can I do the same in a Lambda? Currently, I have to declare a relationship between saying that a Pageview belongs to a User (or a User has many pageviews), and then:

func (p *Pageview) FindAll(userId string, siteID string) ([]byte, error) {
    p.UserID = userID
    p.SiteID = siteID

    db.Find(p)
    return json.Marshal(p)
}

when I want to:

func (p *Pageview) FindAll(siteID string) ([]byte, error) {
    p.SiteID = siteID

    db.Find(p)
    return json.Marshal(p)
}

Is there any other way that I can do it, without having the declare the relationship?

I have never asked myself how is possible to do a query limiting by the current user, without having to declare it in the query itself. Maybe if I understand I can emulate the same behavior.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?