stephenafamo/bob

Join issue with generated models

Closed this issue · 1 comments

When having a model query like:

account, err := model.AccountDetails.Query(
		ctx,
		db,
		model.SelectJoins(ctx).AccountDetails.LeftJoin.AccountBan,
		model.SelectWhere.AccountDetails.AccountID.EQ(accountId),
	).One()

it will lead to nothing from the other table (AccountBan) to be selected.

When running MustBuild() and taking a look at it produces this:

Query: SELECT
*
FROM "account"."details" AS "account.details"
LEFT JOIN "account"."details" AS "account.details" ON ("account.details"."account_id" = "account.ban"."account_id")
WHERE ("account.details"."account_id" = $1)

but when having a bob debug executor the following will be executed, most columns have been removed but the point is that it doesn't select the "account.ban" table anywhere.

SELECT
"account.details"."account_id" AS "account_id", "account.details"."apps" AS "apps"
FROM "account"."details" AS "account.details"
LEFT JOIN "account"."ban" AS "account.ban" ON ("account.ban"."account_id" = "account.details"."account_id")
WHERE ("account.details"."account_id" = $1)
LIMIT 1

Is this a bug or am I using the joins incorrect?

This is expected.

The idea of the JoinHelpers is that if you want to filter by a condition on the other table, it saves the stress of writing the join query manually.

	account, err := model.AccountDetails.Query(
		ctx,
		db,
		model.SelectJoins(ctx).AccountDetails.LeftJoin.AccountBan,
		model.SelectWhere.AccountDetails.AccountID.EQ(accountId),
		model.SelectWhere.AccountBan.Status.EQ("banned"), // for example
	).One()

However, this does not automatically select rows from that table, because it also has to consider where to scan the columns into, and since the query is from the AccountDetails model, it will only return the columns to scan into the AccountDetails.

Now, if you want to select the account.ban relationships, then you can use ThenLoad (or Preload for to_one relationships) query mods, which will load those relationships.