2017-03-06 9 views
0

は、私は以下の表を持っている複数:Sequelize:句

論文 - ユーザ - タグ - フォロワー - Suscribes

条はユーザー(FK:条テーブル内のUSERID)に属し

条を持つことができます多くのタグ。ここで

enter image description here

フォロワー表されています:ここで生成されたtagarticleテーブルがある

enter image description here

そしてSuscribesテーブル:

enter image description here

ユーザーが多くのユーザーに従うことができます国(payId)、タグまたは記事(notif )。

フォローしているユーザーの全記事と特定のユーザーの国またはタグを検索するにはどうすればよいですか?

答えて

1

私はあなたが質問をしていることを前提としています。 私はあなたの質問を正しく理解しているかわかりません。あなたは、2つのクエリを探しています:

  • クエリが加入し、続いユーザーの

    • クエリのすべての記事国/タグ/特定のユーザーの記事、

    私はモデル間で作られた団体から始めましょう。私たちは今、その後、ユーザーのすべての記事を照会することができます上記の関連を使用して

    // in User model definition 
    User.belongsToMany(User, { as: 'Followers', through: 'Followers', foreignKey: 'userId', otherKey: 'followId' }); 
    User.hasMany(Subscribe, { foreignKey: 'userId' }); 
    User.hasMany(Article, { foreignKey: 'userId' }); 
    

    あなたが国を照会したい場合

    { 
        id: 1, 
        Followers: [ 
         { 
          id: 4, 
          Articles: [ 
           { 
            id: 1, 
            title: 'article title' // some example field of Article model 
           } 
          ] 
         } 
        ] 
    } 
    

    と同様の結果を生成するクエリの上

    models.User.findByPrimary(1, { 
        include: [ 
         { 
          model: models.User, 
          as: 'Followers', 
          include: [ models.Article ] 
         } 
        ] 
    }).then(function(user){ 
        // here you have user with his followers and their articles 
    }); 
    

    /tag /記事を特定のユーザーが購読している場合は、別の関連付けをSubscribeにしてください。

    // in Subscribe model definition 
    Subscribe.belongsTo(Tag, { foreignKey: 'tagId' }); 
    Subscribe.belongsTo(Article, { foreignKey: 'articleId' }); 
    Subscribe.belongsTo(Country, { foreignKey: 'payId' }); 
    

    は、今、私たちはあなたが属性TagCountryを入れ子になっていますuser.Subscribes介してアクセスするすべての彼のサブスクリプション、とユーザーを取得する。この例では

    models.User.findByPrimary(1, { 
        include: [ 
         { 
          model: models.Subscribe, 
          include: [ models.Tag, models.Country, models.Article ] 
         } 
        ] 
    }).then(function(user){ 
        // here you get user with his subscriptions 
    }); 
    

    を求めた2番目のクエリを実行するために必要なすべての関連付けを持っており、 Article。ユーザーがTagにサブスクライブしている場合は、CountryArticleの両方がこの場合にはNULLになります。

  • +0

    ありがとうございます。それはまさに私が必要なものです –