【问题标题】:SailsJs - Joining multiple models with criteria on all joined modelsSailsJs - 使用所有连接模型的标准连接多个模型
【发布时间】:2016-04-12 07:47:41
【问题描述】:

下面是我的数据模型,

学校:

  • 学校编号
  • 姓名
  • 状态

游戏:

  • 学校编号
  • 游戏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模型关联来实现它?

【问题讨论】:

    标签: sails.js sails-postgresql


    【解决方案1】:

    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 filter 来清理结果。

    第二种更简单的解决方案是使用.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;
    });
    

    【讨论】:

    • 我想要下面的参与者结果。 [{ StudentID: 111111111, Name: Alex, Status: Active, SchoolID: { SchoolID: 2222222, Name: "St.Jhons", Status: "Active" }, GameID: { SchoolID: 2222222, GameID: 3333333, Name: " Throw Ball", Status: "Active" } }] 只有在 Participant 和他的 Game & School 处于活动状态时,我才应该获取 Participant 详细信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2013-09-30
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多