有许多方法,其中一些记录在 PostGraphile 的文档中的Relations > Many-to-many Relations下。
create function foos_bars(f foos) returns setof bars as $$
select bars.*
from bars
inner join foo_bars
on foo_bars.bar_id = bars.id
where foo_bars.foo_id = f.id
$$ language sql stable;
const { makeExtendSchemaPlugin, gql, embed } = require("graphile-utils");
module.exports = makeExtendSchemaPlugin(build => {
const { pgSql: sql } = build;
return {
typeDefs: gql`
extend type Foo {
bars: BarsConnection @pgQuery(
source: ${embed(sql.fragment`bars`)}
withQueryBuilder: ${embed((queryBuilder, args) => {
queryBuilder.where(
sql.fragment`exists(select 1 from foo_bars where foo_bars.bar_id = ${queryBuilder.getTableAlias()}.id and foo_bars.foo_id = ${queryBuilder.parentQueryBuilder.getTableAlias()}.id`
);
})}
)
}
`,
};
});
(这更高效,但更难阅读 - 我们希望将来优化这种语法)。
yarn add @graphile-contrib/pg-many-to-many
postgraphile --append-plugins @graphile-contrib/pg-many-to-many
还可以优化命名
pg-simplify-inflector
如果您确定不会发生冲突,我们提供了一个插件,可用于简化架构中的名称;如果您的数据库模式定义明确,我强烈建议您使用它:
https://github.com/graphile/pg-simplify-inflector