2017-06-12 6 views
0

PostsUsersの基本アプリケーションがあります。私は、ユーザーがのみ、以下の条件を満たしてポストを提示されていることを確認しようとしている:Sequelize.jsはエイリアスアサーションと非エイリアスアソシエーションを結合します

  1. 彼らはこの記事を見ていない彼らは

するために、この記事の著者ではありません

  • 前にそのため、私はこれらの団体があります。私は、しかし、別のクエリでそれぞれの条件を満足させることができる午前

    User.hasMany(Post, { 
        foreignKey: 'user_id' 
    }); 
    
    User.belongsToMany(Post, { 
        as: { 
        singular: 'ViewedPost', 
        plural: 'ViewedPosts' 
        }, 
        through: UserPostView, 
        foreignKey: 'user_id', 
        otherKey: 'post_id' 
    }); 
    
    Post.belongsToMany(User, { 
        as: { 
        singular: 'ViewUser', 
        plural: 'ViewUsers' 
        }, 
        through: UserPostView, 
        foreignKey: 'post_id', 
        otherKey: 'user_id' 
    }); 
    

    を、私は再びできるようにしたいと思います私の条件を満たす投稿を1回のクエリで回します。

    ここでは、ユーザーがこれまでに見たことのない投稿を取得するために使用しているクエリを示します。ユーザーが作成していない投稿を返すようにこのクエリを変更するにはどうすればよいですか?

    function fetchFreshPost(user) { 
        return user.getViewedPosts({ 
        attributes: ['id'], 
        joinTableAttributes: [] 
        }).then(function(posts) { 
        var postIds = _.map(posts, 'id'); 
        var query = { 
         limit: 1, 
         where: { 
         id: { 
          $notIn: postIds 
         } 
         } 
        }; 
    
        return Post.findAll(query); 
        }) 
    } 
    

    ありがとうございました。

  • 答えて

    0

    あなたは$ NEをADDEことができますwhere句、

    var query = { 
         limit: 1, 
         where: { 
         id: { 
          $notIn: postIds 
         }, 
         user_id : {$ne : user.id} 
         } 
        }; 
    
    +0

    のようなものではおかげで@Keval - 残念ながら、これはまだ2つのクエリ、1 'getViewedPosts'は、ユーザの閲覧の記事を取得するために、次にどこを有する第二が必要です句。私は1つのクエリにこれを組み合わせようとしています。 – lightyrs

    関連する問題