Skip to content

Alias for include models #6007

Closed
Closed

Description

@sohaibfarooqi

Hi,
I want to use alias for include models. I have tried it with this:
ModelA.hasMany(ModelB, {foreignKey: 'ABC'});
ModelB.belongsTo( ModelA, {as: 'XYZ' , foreignKey: 'ABC'});
But this does't work.
I have tried to specify "as" in include model array like:
model: models.ModelB,
required: false,
as: 'Model_ALIAS'
attributes:
[
'id',
'selector',
[sequelize.fn('COUNT', sequelize.col('selector')), 'total_count']
],
group: ['id'],
order: "total_count DESC"

But this throws an error that ModelB (Model_ALIAS) is not associated to ModelA. How can i define an alias to associated model so that all column prefix gets that alias like Model_ALIAS.id?

Activity

  1. mickhansen commented on Jun 1, 2016

    @mickhansen
    Contributor

    The relation and the include needs to use the same alias.
    hasMany(ModelB, {as: 'Model_ALIAS'}

  2. sohaibfarooqi commented on Jun 1, 2016

    @sohaibfarooqi
    Author

    Yes it works perfectly. However i am curious why we have to define the alias in relation as well as in model?

  3. mickhansen commented on Jun 1, 2016

    @mickhansen
    Contributor

    We allow multiple associations between the same models.

  4. anatolii-zolotar commented on Jun 1, 2016

    @anatolii-zolotar

    @mickhansen
    Sorry, I have a similar (imo) problem and don't understand.
    I have two models, for example: Project ----1:N---- Task and use complex query with join to get list of Projects with Tasks count for each Project row. I spent ton of time before I've figured out that if i define

    Task.belongsTo(Project, { foreignKey: 'projectRef' });
    Project.hasMany(Task, { as: 'Tasks', foreignKey: 'projectRef' });
    // or 
    Task.belongsTo(Project, { as: 'Project', foreignKey: 'projectRef' });
    Project.hasMany(Task, { as: 'Tasks', foreignKey: 'projectRef' });
    

    it doesn't work, but if I remove aliases

    Task.belongsTo(Project, { foreignKey: 'projectRef' });
    Project.hasMany(Task, { foreignKey: 'projectRef' });
    

    it works well. So, relating to issue and

    The relation and the include needs to use the same alias.
    hasMany(ModelB, {as: 'Model_ALIAS'}

    if I want to leave
    Project.hasMany(Task, { as: 'Tasks' ...
    alias how should I define as in belongsTo accosiation?

    Thank you for your contribution

    UPD I don't use alias in include, so may be this is a wrong place for my question.

    Project.findAll({ 
        attributes: {
            include: [[Sequelize.cast(Sequelize.fn('COUNT', Sequelize.col('tasks.id')), 'INTEGER'), 'tasksCount']],
        },
        include: {
            model: Task,
            attributes: []
        },
        group: [Sequelize.col('projects.id'), Sequelize.col('tasks.id')]
    })
    
  5. mickhansen commented on Jun 2, 2016

    @mickhansen
    Contributor

    @anatolyzolotar aliases should have no effect on the query actually working, unless you're targetting the old names with raw col matching

  6. chornbe commented on May 7, 2017

    @chornbe

    Let's say I have a simple, but multi-associated model. Something like (to over-use the favorite blog/person example):

    model -> Blog
    model -> Person

    a Blog might have an author, a moderator, and a commenter.

    Can I do something like:

    var Blog = sequelize.define( "Blog", {
    blogName : { type : DataTypes.STRING }
    });

    var Person = sequelize.define( "Person", {
    name : { type : DataTypes.STRING }
    });

    Super simple for this example.

    Can I not then associate Person to Blog three times, using different aliases...

    Person.belongsToMany( models.Blog, { as : "author" } );
    Person.belongsToMany( models.Blog, { as : "moderator" } );
    Person.belongsToMany( models.Blog, { as : "commenter" } );

    Blog.hasMany( models.User, { as : "author" } );
    Blog.hasMany( models.User, { as : "moderator" } );
    Blog.hasMany( models.User, { as : "commenter" } );

    Can I not, then, just use them in an include?

    models.Blog.findAll({
    include : [ "author" ]
    })
    .then( function( blog ){
    // reference blog.author(s) <---- ?
    });

    Nothing approaching this seems to work, and I thought I'd seen something saying that string-based aliases and includes was working.

    Do I have this completely wrong?

    Thanks.

  7. raxod502 commented on Jul 14, 2017

    @raxod502

    Needing to specify the aliases because of multiple associations between the same models makes sense to me, but if I'm using include: [{ all: true }], then why can't Sequelize figure it out? Is include: all really unusable if you use any aliases? Or have I misunderstood what is happening? (It seems that Sequelize drops aliases and queries the default table names, when I use include: all.)

  8. onweer commented on Apr 27, 2018

    @onweer

    Woring with this

    include: [{
            model: this.ctx.model.Item,
            attributes: [[Sequelize.fn('COUNT', Sequelize.col('items.id')), 'itemTotal']],
            through: {
              attributes: [],
            },
            as: 'items',
          }]
    
  9. upasanadash commented on Feb 13, 2019

    @upasanadash

    here how to fetch the name total_count?

  10. upasanadash commented on Feb 13, 2019

    @upasanadash

    resolve: (parent, args, context, resolveInfo) => {
    // return joinMonster.default(resolveInfo,{}, sql => ({

                return MovieDb.models.movie_streams.findAll({
                    distinct: true,
                    attributes:[
                       
                            //  include:[{
                                'series_number',
                    
                                [sequelize.literal('COUNT(DISTINCT(series_number))'), 'total_series'],
                                //  attributes: ['organizationName', 'admin']
    
                                 [sequelize.fn('GROUP_CONCAT', sequelize.literal("DISTINCT(series_number) order by series_number asc  SEPARATOR '||'" )), 'series_number'],
                            //  }]
              ],
                    group: ['movie_id'],
                   where: {movie_id:parent.id, is_episode:1, episode_parent_id:0, is_converted:1 },
                 
                 });
    

    this is my code. In sql we can fetch through two names like total_series and series_number. But how to fetch this name using graphql?

  11. ariful-regfire commented on Apr 9, 2019

    @ariful-regfire

    Model B is associated to Model A using an alias. You must use the 'as' keyword to specify the alias within your include statement.

    But I have added 'as' keyword to the include already. Can anyone help me with this?

  12. omerinjo commented on Apr 5, 2020

    @omerinjo

    you specify alise in parent table .
    example:

    you have two tables user and comments. User is parent of comments 1:N
    foreignKey is in comments table ref to user table (foreignKeys are in childe tables).Sow when you write your associations you set your alies in parent table not in chalde table

    user.hasMany(models.comments, {as:"sometthing":foreignKey :"user_id" }) // user_id is primarykey
    comments.belongsTo(models.user, {foreignKey :"user_id"}) //user_id is foreignKeys

    then when you write method

    users.findAll({
    include:[{
    model:"comments",
    as:"what ever you set in parent table "sometthing""
    }]
    })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions