4

I'm using Sequelize ORM with Node.js and I can't get my head around on how to build the following query with it.

SELECT service.*, serviceCollection.*, client.companyName, client.idclient 
FROM service 
INNER JOIN serviceCollection 
ON service.serviceCollection_idserviceCollection = serviceCollection.idserviceCollection 
INNER JOIN client 
ON serviceCollection.client_idclient = client.idclient

This query works and runs fine when I try it on phpMyAdmin. The complication is that the Client model has no direct relation with Service, so when trying to do this :

Service.findAll({include : [ServiceCollection, Client]}).then(function(service){
    if(service) {
        res.status(200).json(service);
    }
});

I get the following error :

Unhandled rejection Error: client is not associated to service!

How could I prepare the query in a way that would get the client information from the foreignkey in serviceCollection and not the original model - service. I can't just use include on client because it will give me the error, I need to associate it to this query some other way and I can't seem to find the solution in the documentation.

Miguel M.
  • 411
  • 1
  • 4
  • 12
  • 4
    possible duplicate of [How to make join querys using sequelize in nodejs](http://stackoverflow.com/questions/20460270/how-to-make-join-querys-using-sequelize-in-nodejs) – Esso Aug 13 '15 at 09:07

1 Answers1

16

Do you have a relation set up between servicecollection and client? In that case you can do:

Service.findAll({
  include : [
    { 
      model: ServiceCollection, 
      required: true,
      include: [{model: Client, required: true }]}
  ]
});

required: true creates an inner join, the default is a left join

Jan Aagaard Meier
  • 28,078
  • 8
  • 95
  • 66