【问题标题】:Fetch data using where clause on relational model使用关系模型上的 where 子句获取数据
【发布时间】:2020-12-09 10:36:40
【问题描述】:

在环回 3.0 中,我试图在对关系应用 where 子句的同时从多个关系模型中获取数据。

以下是模型的 JSON 示例:

modelA.json
{
    "properties": {
        "id": {
            "type": "string",
            "required": true,
            "length": 20
        },
        "modelBid": {
            "type": "string"
        },
        ...
    }
    "relations": {
        "modelB-rel": {
            "type": "belongsTo",
            "model": "modelB",
            "foreignKey": "modelBid",
            "primaryKey": "id"
        },
        ...
    }
}

modelB.json
{
    "properties": {
        "id": {
            "type": "string",
            "required": "false",
            "length": "20"
        },
        "name": {
            "type": "string",
            "length": "255"
        },
        ...
    }
}

我想要执行的查询的 SQL 等效项:

SELECT * FROM modelA a 
LEFT JOIN modelB b
ON a.modelBid = b.id
WHERE b.name = 'abcd'

我正在使用的环回过滤器对象不提供获取预期结果:

modelA.find({
    include: [
        {
            relation: 'modelB-rel',
            scope: {
                fields: ['id', 'name'],
            },
        }
    ],
    where: {
        modelB-rel: {
            name: 'abcd',
        },
    }
}
...

请帮助我更正过滤器对象以获得与上述 SQL 等效项相同的结果。

【问题讨论】:

    标签: mongodb loopback


    【解决方案1】:

    为了在相关模型上应用过滤器,您必须将过滤器放在包含模型的范围内。你可以使用这样的东西:

    modelA.find({
        include: [
            {
                relation: 'modelB-rel',
                scope: {
                    fields: ['id', 'name'],
                    where: {name: 'abcd'}          
                },
            }
        ],
    })
    

    【讨论】:

    • 这将包括 modelA 的所有记录,并且只过滤 modelB 记录包括在 modelA 对象中,这与提到的 SQL 不等效。
    猜你喜欢
    • 2015-03-12
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    相关资源
    最近更新 更多