In GraphQL we can write the object type in GraphQLList and fetch all the fields. I am using Association and it is joining the two tables but I am unable to fetch the field of both the tables. It only takes the fields what I have written in GraphQLList.As I want the list of data.
Here is the code
films table:
module.exports =(sequelize, DataTypes) => {
const films = sequelize.define(
'films',
{
id:{
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
},
},
);
films.associate = (models) => {
films.hasMany(models.movie_stream, {
foreignKey: 'movie_id',
});
};
return films;
}
movie_stream table:
module.exports = (sequelize, DataTypes) => {
const movie_streams = sequelize.define('movie_streams', {
id:{
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
},
movie_id: {
type: DataTypes.STRING,
foreignKey: "movie_id",
},
});
movie_streams.associate = (models) => {
movie_streams.hasMany(models.films, {
foreignKey: 'id',
});
};
return movie_streams;
};
Schema file:
movieList:{
type: new GraphQLList(Films),
resolve: (parent,args)=>{
return newdb.films.findAll({attributes:['id','name','permalink'],
where: {content_category_value:parent.id },
include: [{
model:newdb.movie_stream,
attributes:['id','movie_id'],
}],
}).then(data=>{
return data;
})
}
Can I write here type: new GraphQLList(Films, MovieStream)??
I have tried but It does not work. Please give me some idea how do I fetch the fields of both the table???
There's two main ways of achieving this in GraphQL: unions and interfaces.
An interface is where two or more object types in your GraphQL schema share certain fields (characteristics). For example you might have a
Product
interface for all the items in your shop, where every product has aprice
,barcode
, andshelfLocation
. All your products, such asShampoo
,Bread
,LawnChair
would then implement this interface.A union is where you declare that something can return more than one object type, but those types don't have to have any properties in common.
In both cases you can query type specific fields using fragments or inline fragments:
You can learn more about this in the GraphQL schema documentation and read about GraphQLInterfaceType and GraphQLUnionType in the GraphQL.js documentation.