Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use UNION in sequelize..?? OR Any other method like UNION expect promise.All...?

I have two tables: tbl_product, tbl_product_category

I want to make an API that take a keyword and return all product and product category that match with the keyword. If the result from tbl_product then it also return that it is product. If the result from tbl_product_category then it also return that it is category.

tbl_product_catagory.findAll({
  raw: true,
  attributes: [[sequelize.literal("catagory_name"), "type"]],
  include: [{
    model: tbl_product,
    attributes: [[sequelize.literal(["product_name"]), "name"]],
    required: false,
    where: {
      product_name: {
        [Op.like]: "%" + data.word + "%"
      }
    }
  }]
})
like image 667
Pradip Bhuvani Avatar asked Jun 22 '18 11:06

Pradip Bhuvani


2 Answers

According to this answer and this answer we can conclude that sequelize don't have good support for unions.

like image 167
Soham Lawar Avatar answered Oct 16 '22 14:10

Soham Lawar


I know this is very old, but i like to show a turnaround using nodejs for this issue because sequelize yet do not have union support. Is very simple but sometimes we don't realize this:

Example:

Promise.all([
    Blog.findAll({ include: { model: Author, required: true } }),
    Blog.findAll({ include: { model: AnonymInfo, required: true } }),
]).then((modelReturn) => resolve(modelReturn.flat()))
like image 42
Vinicius França Avatar answered Oct 16 '22 14:10

Vinicius França