从两个模型返回数据

时间:2014-06-07 13:48:07

标签: javascript mysql node.js sails.js

  

你好,伙计们。请帮我。我如何才能获得'主题'数组并将其附加到res.view()。我试过很多变种。但总是在'主题'我找不到了#39;


Subjects.query("SELECT `subjects`.`id`, `subjects`.`name` AS `subject`  FROM `subjects`  
                WHERE `subjects`.`faculty` = " + faculty_id, function (err, subs)  
{  
     subs.forEach(function(subject, topics)  
     {  
         var topics = new Array();   
         Topics.query("SELECT `topics`.`id`, `topics`.`name` AS `topic` FROM `topics`  
                       WHERE `topics`.`subject` = " + subject.id, function (err, tops)  
         {  
             topics[subject.id] = tops;  
         });  
         console.log(topics);
     });  
     res.view({  
                  title: 'Private cabinet',  
                  users: user[0],   
                  subjects: subs,
     });  
});

1 个答案:

答案 0 :(得分:0)

我尝试了很多变体,但只有这个有效:

var async  = require('async');
_ = require('lodash');  
module.exports = {  
'cabinet': function (req, res)
{
    async.auto(
    {
        user: function(cb)
        {
            User.query("SELECT `users`.`email`, `users`.`id`, `users`.`name`, `users`.`surname`, `users`.`lastname`, `groups`.`name` as `group`, `faculties`.`name` as `faculty`, `faculties`.`id` AS `faculty_id` FROM `users`, `groups`, `faculties` WHERE `users`.`id` = " + req.session.user + " AND `users`.`group` = `groups`.`id` AND `faculties`.`id` = `groups`.`faculty` GROUP BY `users`.`id`", cb);
        },

        subjects: ['user', function(cb, async_data)
        {
             var faculty = async_data.user.map(function (item){return item.faculty_id});
             Subjects.find()
                .where({faculty: faculty})
                .exec(cb);
        }],

        topics: ['subjects', function(cb, async_data)
        {
             var subject = async_data.subjects.map(function (item){return item.id});
             Topics.find()
                .where({subject: subject})
                .exec(cb);
        }]
    },
    function allDone (err, async_data) 
    {
        if (err) return res.serverError(err);
        var user = async_data.user;
        var subjects = async_data.subjects;
        var topics = async_data.topics;
        _.map(user, function (user) {
        var theseSubjects =
            _.where(subjects, {faculty: user.faculty_id });
            subjects = theseSubjects;
            _.map(subjects, function (subject) {
            var theseTopics =
                _.where(topics, {subject: subject.id });
            subject.topics = theseTopics;
            });
        });
        res.view({
            title: 'Личный кабинет',
            user: user[0],
            subjects: subjects
        });
    });
},