Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize include even if it's null

I am using Sequelize express with Node.js as the backend, some data from my sequelize I need to include to another table but some of these data is null so the whole result I’m getting is null.

Question: how can I return some data if data it's available and return the other null if not data is there

router.get("/scheduled/:id", function(req, res, next) {

    models.Order.findOne({

        where: {
            id: req.params.id
        },
        attributes: ['orderStatus', 'id', 'serviceId', 'orderDescription', 'orderScheduledDate'],
        include: [{
            model: models.User,
            attributes: ['firstName', 'phoneNumber']
        }]
    }).then(function(data) {

        res.status(200).send({
            data: data,
            serviceName: data["serviceId"]
        });

    });

});

I want: the result should return null if there is no user for the order and return order details and user when it is null.

like image 540
Faisal Avatar asked May 01 '17 10:05

Faisal


1 Answers

However, a where clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add required: false for more detail check nested-eager-loading

var users  = require('./database/models').user;

    models.Order.findOne({
    where: {
        id: req.params.id
    },attributes: ['orderStatus','id','serviceId','orderDescription','orderScheduledDate'],
    include: [
        {model: users,required: false,
        attributes: ['firstName','phoneNumber']
        }
    ]
}).then(function(data) {

    res.status(200).send({data : data,serviceName : data["serviceId"]});

});
like image 94
Adiii Avatar answered Oct 13 '22 12:10

Adiii