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

One-to-many support in joins #93

Merged
merged 4 commits into from
May 27, 2024
Merged

One-to-many support in joins #93

merged 4 commits into from
May 27, 2024

Conversation

igorbenav
Copy link
Owner

@igorbenav igorbenav commented May 26, 2024

One-to-many support in joins

This fixes #91. Btw I'm not completely satisfied with the implementation, but it's enough for now.

  • Assuming a card has multiple articles, articles in get_joined response should be a list of articles.
  • Assuming a card has multiple articles, articles in get_multi_joined response should be a list of articles.
  • Add a way to specify if one-to-many or one-to-one
  • Tests covering changes
  • Documentation updates

Documentation

Handling One-to-One and One-to-Many Joins in FastCRUD

FastCRUD provides flexibility in handling one-to-one and one-to-many relationships through get_joined and get_multi_joined methods, along with the ability to specify how joined data should be structured using both the relationship_type (default one-to-one) and the nest_joins (default False) parameters.

One-to-One Relationships

  • get_joined: Fetch a single record and its directly associated record (e.g., a user and their profile).
  • get_multi_joined (with nest_joins=False): Retrieve multiple records, each linked to a single related record from another table (e.g., users and their profiles).
Example

Let's define two tables:

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    tier_id = Column(Integer, ForeignKey("tier.id"))

class Tier(Base):
    __tablename__ = "tier"
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)

Fetch a user and their tier:

user_tier = await user_crud.get_joined(
    db=db,
    join_model=Tier,
    join_on=User.tier_id == Tier.id,
    join_type="left",
    join_prefix="tier_",
    id=1
)

The result will be:

{
    "id": 1,
    "name": "Example",
    "tier_id": 1,
    "tier_name": "Free"
}
One-to-One Relationship with Nested Joins

To get the joined data in a nested dictionary:

user_tier = await user_crud.get_joined(
    db=db,
    join_model=Tier,
    join_on=User.tier_id == Tier.id,
    join_type="left",
    join_prefix="tier_",
    nest_joins=True,
    id=1
)

The result will be:

{
    "id": 1,
    "name": "Example",
    "tier": {
        "id": 1,
        "name": "Free"
    }
}

One-to-Many Relationships

  • get_joined (with nest_joins=True): Retrieve a single record with all its related records nested within it (e.g., a user and all their blog posts).
  • get_multi_joined (with nest_joins=True): Fetch multiple primary records, each with their related records nested (e.g., multiple users and all their blog posts).

Warning

When using nest_joins=True, the performance will always be a bit worse than when using nest_joins=False. For cases where more performance is necessary, consider using nest_joins=False and remodeling your database.

Example

To demonstrate a one-to-many relationship, let's assume User and Post tables:

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary key=True)
    name = Column(String)

class Post(Base):
    __tablename__ = "post"
    id = Column(Integer, primary key=True)
    user_id = Column(Integer, ForeignKey("user.id"))
    content = Column(String)

Fetch a user and all their posts:

user_posts = await user_crud.get_joined(
    db=db,
    join_model=Post,
    join_on=User.id == Post.user_id,
    join_type="left",
    join_prefix="post_",
    nest_joins=True,
    id=1
)

The result will be:

{
    "id": 1,
    "name": "Example User",
    "posts": [
        {
            "id": 101,
            "user_id": 1,
            "content": "First post content"
        },
        {
            "id": 102,
            "user_id": 1,
            "content": "Second post content"
        }
    ]
}

@igorbenav igorbenav added bug Something isn't working enhancement New feature or request FastCRUD Methods Related to FastCRUD methods labels May 26, 2024
Copy link

codecov bot commented May 26, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (03d4a2d) to head (8191543).

Additional details and impacted files
@@            Coverage Diff             @@
##              main       #93    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           68        70     +2     
  Lines         4819      5429   +610     
==========================================
+ Hits          4819      5429   +610     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@igorbenav igorbenav changed the title [WIP] Nested Join fixes One-to-many support in joins May 27, 2024
@igorbenav igorbenav merged commit 43529fd into main May 27, 2024
16 checks passed
@igorbenav igorbenav deleted the nested-fix branch May 27, 2024 07:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working enhancement New feature or request FastCRUD Methods Related to FastCRUD methods
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Nested Join Should Return List When Necessary
1 participant