1

下面是我的数据模型,

学校:

  • 学号
  • 姓名
  • 地位

游戏:

  • 学号
  • 游戏ID
  • 姓名
  • 地位

参与者:

  • 学号
  • 游戏ID
  • 学生卡
  • 姓名
  • 地位

我想根据“参与者”、“学校”和“游戏”的“状态”显示“参与者”。检索时是否可以过滤结果?

我要执行的查询是,

select *
from
    Participants
    inner join Game on Participants.GameID = Game.GameID
    inner join School on Game.SchoolID = School.SchoolID
where
    Participants.Status="Active"
    and Game.Status="Active"
    and School.Status="Active"

我如何使用sailsjs模型关联来实现它?

4

1 回答 1

0

Sails.js/Waterline 中还没有内置的方式来填充深层嵌套关联。

你需要这样的模型:

游戏:

attributes:{
    SchoolID:{
        model: 'School'
    }
    // rest of attributes
}

参与者:

attributes:{
    SchoolID:{
        model: 'School'
    },
    GameID:{
        model: 'Game'
    }
    // rest of attributes
}

比查询:

Game.find({Status:"Active"})
    .populate("School",{
        where: {
            Status: "Active"
        }
    })
    .populate("Participants",{
        where: {
            Status: "Active"
        }
    }).exec(function (err, result){
        return result
    });

现在是棘手的部分。您将获得带有活跃游戏的 Array。不管他们是否有活跃的学校或参与者。结果将有 2 个子数组:参与者和学校。如果它们不是空的,那就是你的结果。

[
    {
        SchoolID: [],
        GameID: [],
        Name: '',
        Status: ''
    },
    {
        SchoolID: [SchoolID: 1, Name: '', Status: 'Active'],
        GameID: [SchoolID: 1, GameID: 1, Name: '', Status: 'Active'],
        Name: '',
        Status: ''
    }
]

您可以使用lodash 过滤器来清理结果。

第二种解决方案更简单的是使用.query()

您可以只使用您编写的查询:

School.query('select * from Participants inner join Game on Participants.GameID=Game.GameID inner join School on Game.SchoolID=School.SchoolID where Participants.Status="Active" and Game.Status="Active" and School.Status="Active"', function(err, results) {

    return results;
});
于 2016-04-12T08:51:40.703 回答