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

Add RelationWithOpts to SelectQuery for Customizing JOIN ON Clause #1097

Merged
merged 1 commit into from
Jan 3, 2025

Conversation

takaaa220
Copy link
Contributor

@takaaa220 takaaa220 commented Jan 2, 2025

Description

Closes #554.

This PR introduces a new method, RelationWithOpts, to the SelectQuery interface. This method allows users to customize the JOIN ON clause when defining relationships between models (e.g., has-one, has-many).

Key Points of Discussion

Current Behavior: The existing Relation method allows applying filters to the joined table's SELECT query but does not modify the JOIN ON clause. For example(it is on #554):

q := repo.db.NewSelect().Model(&product)
q.Relation("Stock", func(q *bun.SelectQuery) *bun.SelectQuery {
    return q.Where("branch_id = ?", filter.BranchId)
})
  • I believe it's essential to preserve this behavior to maintain backward compatibility and separation of concerns (filtering the joined table vs. customizing JOIN ON).
  • Proposed Changes: The RelationWithOpts method provides an additional option to customize the JOIN ON clause while keeping the existing functionality of Relation.

Example Usage

Here is a quick example of how RelationWithOpts can be utilized:

q := repo.db.NewSelect().Model(&product)
q.RelationWithOpts("Stock", &bun.RelationOpts{
	AdditionalJoinOnConditions: []schema.QueryWithArgs{
		{
			Query: "stock.quantity = ?",
			Args:  []any{1},
		},
	},
})

I add this feature but actually i don't like this feature itself and the interface very much (especially, i don't like to directly face []schema.QueryWithArgs). Feedback and suggestions for improving the interface and functionality are welcome. Let me know your thoughts! (If this feature is deemed unnecessary, please feel free to close this pull request without hesitation.)

@j2gg0s
Copy link
Collaborator

j2gg0s commented Jan 3, 2025

I will release v1.2.9 in the next few days.

@j2gg0s j2gg0s merged commit cbb687d into uptrace:master Jan 3, 2025
4 checks passed
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

Successfully merging this pull request may close these issues.

How to add custom where clause on Relation?
2 participants