Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multiple INNER JOINS with Sequelize ORM

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.

like image 957
Miguel M. Avatar asked Dec 05 '22 02:12

Miguel M.


1 Answers

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

like image 69
Jan Aagaard Meier Avatar answered Dec 09 '22 14:12

Jan Aagaard Meier