join-monster icon indicating copy to clipboard operation
join-monster copied to clipboard

Provide data from many-to-many join tables.

Open naturalethic opened this issue 10 years ago • 17 comments

We store data about a relationship between to entities in their cross join table. Consider a schema where there is a person, an organization and a personOrganization cross table. In the cross table we will store a role field. I would like to be able to discover that information with a graphql query such that:

{
  person {
    organization {
      role
    }
  }
}

Does this seem rational? It may be that I will have to define that property on the organization type and determine from the context of the lookup to query that cross table, and do this outside of Join Monster.

naturalethic avatar Nov 17 '16 22:11 naturalethic

Yeah this is something that needs to be added. We assumed that no info would be fetched from a cross table other than the foreign keys. This capability will be in a future version. For now you can do something like this

{
  person {
    membership {  # add this field to map to the cross table
      role
      organization {
        whateverField
      }
    }
  }
}

Another GraphQLObjectType in between the two fields. In the above example, a membership object could map to your cross table.

acarl005 avatar Nov 18 '16 00:11 acarl005

Thanks, that looks like a workable solution.

naturalethic avatar Nov 18 '16 00:11 naturalethic

I think the query without the person context ( ie. the 3rd relationship key ) is;

SELECT
"public"."person".name,
"public"."organisation".name,
"public"."role".rolename
FROM
"public"."person"
LEFT JOIN "public".personOrganisation ON "public"."person"."id" = "public".personOrganisation."person"
LEFT JOIN "public"."organisation" ON "public".personOrganisation."organisation" = "public"."organisation"."id"
LEFT JOIN "public".organisationRole ON "public"."organisation"."id" = "public".organisationRole."organisation"
LEFT JOIN "public"."role" ON "public".organisationRole."role" = "public"."role"."id"

and with the 3rd key, a simple AND is applied to the JOIN condition as;

SELECT
"public"."person".name,
"public"."organisation".name,
"public"."role".rolename
FROM
"public"."person"
LEFT JOIN "public".personOrganisation ON "public"."person"."id" = "public".personOrganisation."person"
LEFT JOIN "public"."organisation" ON "public".personOrganisation."organisation" = "public"."organisation"."id"
LEFT JOIN "public".organisationRole ON "public"."organisation"."id" = "public".organisationRole."organisation" 
  AND "public"."person"."id" = "public".organisationRole."person"
LEFT JOIN "public"."role" ON "public".organisationRole."role" = "public"."role"."id"

I have a similar problem at the moment, and it seems to me that this question is more about the JOIN condition and less about retrieving fields in the crosstable ( eg, a weight field for the strength of the relationship).

if the organisationRoles is a many-many relationship then providing a 3rd argument to each function in the sqlJoins array could be a non-breaking change that could be powerful.

The 3rd argument could be a map: { <GraphQLObjectType.name> : <GraphQLObjectType.sqlTable> } enabling us to do determine if an ObjectType exists in the query, and if so, apply its context.

sqlJoins: [
 ( table, crossTable, contexts ) => {
  var frag = `${table}.id = $(crossTable).organisation`
  if( contexts.Person ) frag += ` AND $(contexts.Person).id = $(crossTable).person
  return frag;
}
 ...
] 

I'm not completely familiar with the source and its feasibility in consideration of the execution chain, but it feels like something that could be useful in more than one scenario.

Verikon avatar Nov 29 '16 13:11 Verikon

I take that back @naturalethic 's question is clearly about cross table data retrieval. I still submit the above for consideration, even if a variation.

Verikon avatar Nov 29 '16 13:11 Verikon

+1 to this, I also have many use cases where I need to retrieve data from the cross table, but don't want to add another object in the middle as the workaround suggests.

seratonik avatar Feb 07 '17 06:02 seratonik

@Verikon GraphQL args and context object were added to the sqlJoin function signature.

acarl005 avatar Feb 07 '17 08:02 acarl005

@acarl005 what's the status here? Do you still need help enhancing it?

tonyxiao avatar Mar 22 '17 06:03 tonyxiao

@acarl005 any update regarding this? This is the only feature preventing me from using join-monster.

dustinsanders avatar Mar 29 '17 17:03 dustinsanders

Mentally blocked by some issues with paginated many-to-many fields. Still working on it. There are some important deadlines looming here at work so it'll be a few weeks before I can get back on it.

In the meantime, I would love some suggestions on the API, as I have not yet finalized it. It needs the ability to "merge in" columns from the junction table (cross table), at the field level.

acarl005 avatar Mar 29 '17 18:03 acarl005

See my initial thoughts in the code sample below. My thought was to add the field junctionTable on the root of the type, and if that is added then you can use junctionField on the field level.

const UserDefinition = {
  name: 'Users',
  sqlTable: 'users',
  uniqueKey: 'id',
  fields: () => ({
    id: {
      type: GraphQLInt,
    },
    first_name: {
      type: GraphQLString,
    },
    last_name: {

    }
    organizations: {
      type: new GraphQLList(UserOrganization),
      sqlJoins: [
        ( userTable, junctionTable ) =>
          `${userTable}.id = ${junctionTable}.user_id`,
        ( junctionTable, orgTable ) =>
          `${junctionTable}.organization_id = ${orgTable}.id`,
      ]
    },
  })
}

const User = new GraphQLObjectType(UserDefinition)

const OrganizationDefintion = {
  name: 'Organization',
  sqlTable: 'organization',
  uniqueKey: 'id',
  fields: () => ({
    id: {
      type: GraphQLInt,
    },
    name: {
      type: GraphQLString,
    },
    users: {
      type: new GraphQLList(OrganizationUser),
      sqlJoins: [
        ( orgTable, junctionTable ) =>
          `${orgTable}.id = ${junctionTable}.organization_id`,
        ( junctionTable, userTable ) =>
          `${junctionTable}.user_id = ${userTable}.id`,
      ]
    }
  })
}

const Organization = new GraphQLObjectType(OrganizationDefintion)

const UserOrganization = new GraphQLObjectType({
  ...OrganizationDefintion,
  name: 'UserOrganization',
  junctionTable: 'user_organization',
  fields: () => ({
    ...OrganizationDefintion.fields,
    role: {
      type: GraphQLInt,
      junctionField: true,
    },
  })
})

const OrganizationUser = new GraphQLObjectType({
  ...UserDefinition,
  name: 'OrganizationUser',
  junctionTable: 'user_organization',
  fields: () => ({
    ...UserDefinition.fields,
    role: {
      type: GraphQLInt,
      junctionField: true,
    }
  }),
})

dustinsanders avatar Apr 05 '17 03:04 dustinsanders

This feature is added in this commit 3b95f84f2b47fc075772b89f11d89889d9181ee2. It won't be in the main branch until the release of version 2. I hope to have this release within the next couple of months.

acarl005 avatar Jun 06 '17 05:06 acarl005

@acarl005 super exciting to hear about join-monster's support for grabbing data from junction tables-- we literally ran into this problem earlier today.

Do you know if this will work well with graphql-relay-js and its edgeFields property? We'd love to be able to return data onto a Relay-complaint edge. It would be legendary to have something like

export const EventsConnection = connectionDefinitions({
    nodeType: Event,
    edgeFields: {
        providerRef: {
            type: GraphQLString,
            sqlColumn: 'provider_ref',
        },
    },
    connectionFields: {
        count: {
            type: GraphQLInt,
            resolve: ({ edges }) => edges.length,
        },
    },
}).connectionType;

Thanks for all the work you do :)

bw avatar Jun 06 '17 19:06 bw

@acarl005 I just wanted to follow up on this, curious if there is now a way to do this since it was mentioned in the changelog for v2.

Since it wasn't documented yet, I read through the source code to see that we should add the edge field via include (not sure if this is right) on the junction. Our code roughly looks like this:

// Contrived example
eventsConnection: {
  // Other properties that define a connection
  junction: {
    sqlTable: 'name_of_contact_events_join_table',
    sqlJoins: [
      (thisTable, linkTable) => `${thisTable}.id = ${linkTable}.contact_id`,
      (linkTable, foreignTable) => `${linkTable}.event_id = ${foreignTable}.id`,
    ],
    include: {
      // We want to fetch the `metadata` from the join table here and then put it on the edge
      metadata: {
        sqlColumn: 'metadata',
        jmIgnoreAll: false // Side point: this doesn't seem to do anything...
      },
    },
  },
}

But this doesn't fetch the field (when we log the SQL query that join-monster generates, there is no mention of the metadata field). Additionally, trying to request the field in a variety of ways also doesn't work:

Requesting from the Relay-spec connection definition, on the edge
export const EventsConnection = connectionDefinitions({
  nodeType: Event,
  ...
  edgeFields: {
    metadata: {
      type: GraphQLJSON,
    },
  },
}).connectionType;
Requesting from the Relay-spec connection definition, on the edge (but with jmIgnoreAll: true)
export const EventsConnection = connectionDefinitions({
  nodeType: Event,
  ...
  edgeFields: {
    metadata: {
      type: GraphQLJSON,
      jmIgnoreAll: true,
    },
  },
}).connectionType;
Trying to access it from the parent node, as suggested in replies above
metadata: {
  type: GraphQLJSON,
  jmIgnoreAll: true,
}
Trying to access it from the child node, as suggested in replies above
metadata: {
  type: GraphQLJSON,
  jmIgnoreAll: true,
}

.

When we try to print out everything that the Relay-spec connection definition edge is given, we see that there's no relevant data included:

edgeFields: {
  metadata: {
    type: GraphQLJSON,
    resolve: (everything) => console.log(everything),
  },
},

I definitely don't want to hassle you as I can only imagine how much effort it is to maintain a package like this, so I've tried to include as much information as possible. I feel like maybe I'm missing something simple here?

Again, thanks for all the work you do.

bw avatar Jul 06 '17 22:07 bw

OK-- a quick update as I've done more testing. I think I understand how this is structured now and what we were missing.

Under the junction of the connection, we need to add the field which is rendered onto the child node and not the edge:

        include: {
          edge_metadata: {
            sqlColumn: 'metadata',
            jmIgnoreAll: false,
          },
        },

Because it's rendered on the child node, we need to catch it on the other end by creating a field for it:

    edge_metadata: {
      type: GraphQLJSON,
      jmIgnoreAll: true,
      resolve: ({ edge_metadata }) => edge_metadata,
    },

Then such a field would be accessible from the edge (by literally grabbing it off of the node):

  edgeFields: {
    metadata: {
      type: GraphQLJSON,
      resolve: ({ node: { edge_metadata: metadata } }) => metadata,
    },
  },

Crucially, the field must be requested from the child node for it to be written into the SQL query.

# This will work, but only because we're requesting edge_metadata on the child node
connection {
  edges {
    metadata  # This is where we want the field...
    node {
      edge_metadata
    }
  }
}

# This will not work
connection {
  edges {
    metadata  # This will return null
    node {
      # Some other field
    }
  }
}

I know @dustinsanders and a few others were advocating for this structure but this seems very confusing-- fields that belong on the edge shouldn't be rendered onto the child node, by default. If the data needs to be on the child node (e.g. someone is not using the connection/edge/node model and there is no "edge" layer), then maybe we can add a flag?

At the very least, is there a possibility we can allow for some way to render data from the edge on the edge...?

bw avatar Jul 06 '17 22:07 bw

Whoops. I just realized I forgot to add this to the documentation... I will add ASAP.

@bw I agree that for the connection types, it would be intuitive for the junction table's fields to appear on edges. However, I wanted both the paginated and non-paginated fields to be consistent in their interface and in their implementation. This approach seemed the simplest. Placing them on the edge is a separate option that I will consider. Can you open a separate issue for that? Once I update the docs I'll be closing this issue.

acarl005 avatar Jul 07 '17 00:07 acarl005

@acarl005 sure, I'll open a ticket. I'll describe some use cases and other thoughts in the ticket; thanks!

bw avatar Jul 07 '17 00:07 bw

Docs updated here

acarl005 avatar Jul 13 '17 04:07 acarl005