2016-04-06 9 views
1

Das sind meine Tabellen (nicht alle Spalten enthalten) und Beziehungenin SequelizeJS

var client = schema.define('client', { 
    name: { 
     type: Sequelize.STRING, 
     allowNull: false 
    }, 
} 

var task = schema.define('task', { 
    name: { 
     type: Sequelize.STRING, 
     unique: true, 
     allowNull: false 
    }, 
    description: { 
     type: Sequelize.STRING, 
    } 
} 

var clientTask = schema.define('clientTask', { 
    value: { 
     type: Sequelize.STRING, 
     allowNull: false, 
     defaultValue: false 
    }, 
} 

client.belongsToMany(task, { through: clientTask }); 
task.belongsToMany(client, { through: clientTask }); 

ich nur name von Aufgabe zu bekommen und value von clientTask, wurde ich von Client-ID suchen und hier was ich bisher versucht habe.

client.findAll({ 
    attributes: [], 
    where: {id: clientId}, 
    include: [{ 
     model: task, 
     attributes: ['name'] 
    }] 
}).then(function (clients) { 
    //client.tasks is array with task objects(models) with only name attribute 
    //client.tasks[0].clientTask is object(models) with all attributes but I want only `value` 
} 

Im Grunde, was ich will, ist diese Abfrage

Select 
    tasks.name, 
    clienttasks.value 
From 
    clients Inner Join 
    clienttasks 
    On clienttasks.clientId = clients.id Inner Join 
    tasks 
    On clienttasks.taskId = tasks.id 
Where clients.id = ? 

Antwort

0

Sie es wie folgt

clients.findById(1, { 
    attributes: ['id'], 
    include: [{ 
     model: tasks, 
     attributes: ['name'], 
     required: false 
    }] 
}).then(function(client) { 
    return client.tasks.map(function(task) { 
     return { 
      name: task.name, 
      value: task.clients_tasks.value 
     }; 
    }); 
}).then(function(result) { 
    console.log(result); 
    // The rest of you logic here... 
}); 
nicht abfragen