我有一个包含三个孩子的模型Newsfeed
,NewsfeedImage
,NewsfeedText
和NewsfeedLink
。
新闻源
NewsfeedImage
NewsfeedLink
NewsfeedText
从三个子模型中可以看出,每个模型代表一种不同类型的新闻源对象。我的问题是,我如何select *
来自Newsfeed
并包含每个附属儿童模型?期望的输出(忽略JSON):
[{
"id": "1",
"userId": "1",
"commentCount": "0",
"likeCount": "0",
"updatedAt": "2015-12-13 12:12:32",
"createdAt": "2015-12-13 12:12:32",
"newsfeedId": "1",
"model": "1",
"imgUrl": "http://i.imgur.com/...",
"title": "Has anyone..."
}, {
"id": "1",
"userId": "1",
"commentCount": "0",
"likeCount": "0",
"updatedAt": "2015-12-13 12:12:32",
"createdAt": "2015-12-13 12:12:32",
"newsfeedId": "2",
"model": "2",
"linkShort": "http://goo.gl/...",
"linkLong": "http://www....",
"title": "Has anyone ...?"
}, {
"id": "1",
"userId": "1",
"commentCount": "0",
"likeCount": "0",
"updatedAt": "2015-12-13 12:12:32",
"createdAt": "2015-12-13 12:12:32",
"newsfeedId": "3",
"model": "3",
"body": "How much ...?",
"title": "Question ..."
}]
我最初尝试使用连接,但数据交叉不正确。感谢您的帮助,感谢您抽出宝贵的时间来查看我的问题。
答案 0 :(得分:0)
SQL查询:
SELECT * FROM Newsfeed
LEFT JOIN (
SELECT newsfeedId, model, imgUrl,
null AS linkShort, null AS linkLong, null AS body,
title
FROM NewsfeedImage
WHERE NewsfeedImage.newsfeedid = Newsfeed.id
UNION ALL
SELECT newsfeedId, model, null AS imgUrl,
linkShort, linkLong, null AS body,
title
FROM NewsfeedLink
WHERE NewsfeedLink.newsfeedid = Newsfeed.id
UNION ALL
SELECT newsfeedId, model, null imgUrl,
null AS linkShort, null AS linkLong, body,
title
FROM NewsfeedText
WHERE NewsfeedText.newsfeedid = Newsfeed.id
) t
并在程序脚本中删除null
个字段。