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

many2many table with extra field #1420

Open
julienkosinski opened this issue Oct 8, 2019 · 2 comments
Open

many2many table with extra field #1420

julienkosinski opened this issue Oct 8, 2019 · 2 comments

Comments

@julienkosinski
Copy link

julienkosinski commented Oct 8, 2019

I would need to specify a custom extra field to my many2many join table.

What I have in mind is the ability to specify a struct containing all the fields of the join table. This setting would throw an error if the struct does not contain mandatory taged fields.

Thanks!

@elliotcourant
Copy link
Collaborator

Would you be able to provide a simple code example of what you're trying right now and how you would like it to behave?

@thecampagnards
Copy link

thecampagnards commented Nov 8, 2021

Hello,
I think I am in the same situation

Here an example:

I have a many2many table with an extra column, like this:

CREATE TABLE "a" (
    "id" bigserial primary key NOT NULL
);

CREATE TABLE "b" (
    "id" bigserial primary key NOT NULL
);

CREATE TABLE "a_to_b" (
    "a_id" bigint NOT NULL references "a"("id"),
    "b_id" bigint NOT NULL references "b"("id"),
    "extra" bigint NOT NULL
);

I'm trying to Select it via query Relation + ColumnExpr:

// db.go
type A struct {
	tableName struct{} `sql:"a"` // nolint: structcheck, unused
	ID int64           `sql:"id"`
}

type B struct {
	tableName struct{} `sql:"b"` // nolint: structcheck, unused
	ID int64           `sql:"id"`
}

// main.go
type A struct {
	db.A `pg:",inherit"`
	Bs []*db.B `pg:"many2many:a_to_b"`
}

type B struct {
	db.B `pg:",inherit"`
	Extra int64
}

func main(){
    // ...
    var As []*A
    query := dbh.Model(&As).
    Relation("Bs").
    ColumnExpr("a_to_b.extra AS b.extra") // doesnt work

    count, err := query.SelectAndCountEstimate(100) // fail
}

I have this error:

ERROR #42601 syntax error at or near "."

If I switch the . with __, I have this error:

missing FROM-clause entry for table "a_to_b"

I feel I'm doing it wrong but I haven't found any place on how to do
Thanks !

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

3 participants