79206306

Date: 2024-11-20 08:10:18
Score: 1
Natty:
Report link

I have found solution, also I appreciate Anatoly's answer which helps me a lot. there 2 way we can achieve this query using that alias or using model it's self .

In alias way we could call the alias we assigned to user in m2m relation then add get before so in my case would be getBookmarkedPosts , in parentheses as like other queries we could user where or anything we want but unfortunately there is no ide or editor support for it we have to write it by our hands. the code would be followed

let posts=await user.getBookmarkedPosts({
      where:{
        is_active:true
      },
      attributes:['id','image','name'],
      through:{
// it's said that would remove junction table when empty array 
        attributes:[]
      }
     })

But I have problem with this way! the junction table would not remove by adding the attributes:[] and maybe I have made mistake if you know please comment for me and other to learn it.

The other way which helped me a lot is using the model own self and alias. we would user User model then findAll and by providing where we would say only the user requested and then we would add include where we have to bring the post to play. in include we have to give our alias else would fetch written posts instead of bookmarked , and other parts are same you could use attributes in the include part to say only what you want from that model. The most important par is that we add through here and then empty array for attributes field to remove junction table per post returned .

the query would look like this

 let posts = await User.findAll({
        where: {
          id: req.user.id, // filtering for requesting user
        },
        attributes: [], // not including profile info 
        include: [
          {
            model: Post,
            through: {
              attributes: [],// removing junction
            },
            attributes: ["id", "image", "name"], // limiting needed attributes
            as: "BookmarkedPosts", // alias we assigned
            where: {
              is_active: true, // querying the active post
            },
          },
        ],
      });

I hope this help other

Reasons:
  • Blacklisted phrase (1): helped me a lot
  • Whitelisted phrase (-1): hope this help
  • RegEx Blacklisted phrase (1): I have made mistake if you know please
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Abolfazl Mashhadi