简体   繁体   中英

How to get posts by member?

I want to get a post written by a member. in mypage. But all posts by all members are loaded.

user.nick works fine. user.id is stored in post. I tried to compare user.id == post.id but it failed.

What I did.

page.js

router.get('/', (req, res, next) => {
Post.findAll({    
  include: [{
    model: User,
    attributes : ['id', 'nick']
    // where : { id: req.user}
    // where: { id : Sequelize.col('Post.id') }
    }],
  })
    .then((Post) => {
      res.render('mypage', {
        Post: req.food,
        twit : Post,
        user: req.user,
        loginError: req.flash('loginError'),
      });
      console.log(JSON.stringify(Post))
    })
    .catch((error) => {
      console.error(error);
      next(error);
    });

mypage.ejs

<% if(user && user.id) { %>
              <h4>  <%= user.nick %></h2></a>               
                <h4> not <%= twit.posts %></h2></a>               
              <% for ( var i = 0; i < twit.length; i++){ %>
                <h4>  <%= twit[i].posts%></h2></a>
                <h4>  <%= twit[i].id %></h2></a>
                <h4>  <%= twit[i].user.nick %></h2></a>

                  <% } %>
                  <% } %>

index.js

db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.User = require('./user')(sequelize, Sequelize);
db.Post= require('./Post')(sequelize, Sequelize);

db.User.hasMany(db.Post);
db.Post.belongsTo(db.User);

This is where you are doing it wrong:

Post.findAll({    
  include: [{
    model: User,
    attributes : ['id', 'nick']
    // where : { id: req.user}
    // where: { id : Sequelize.col('Post.id') }
    }],
  })

In the above code, you are just including the user object to the post object. It returns all the posts with the associated users .

Instead, when you add a hasMany association between User and Post , user instances have access to hasPosts .

req.user.
    getProducts().
       then((posts) => {
         res.render('mypage', {
            Post: req.food,
            twit : posts,
            user: req.user,
            loginError: req.flash('loginError'),
         });
         console.log(JSON.stringify(posts))
       })
       .catch((error) => {
          console.error(error);
          next(error);
    });

You can query the post which is created by the user like this, if req.user is id of that user :

Post.findAll({
    where : { user_id : req.user } // <----- HERE
    include: [{
        model: User,
        attributes: ['id', 'nick']
    }]
})

And if you do not need the user's information with post you can also remove the include

Post.findAll({
    where : { user_id : req.user }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM