2 回答

TA貢獻2036條經驗 獲得超8個贊
我可以建議我以前使用過的另一種方法。
在這種情況下,您在查詢中生成標簽的 json 并將其返回。
優點:您有 1 次調用 db,它聚合數據,您所要做的就是將 json 解析為一個數組。
缺點:有點難看。請隨意抨擊我。
type jointItem struct {
Item
ParsedTags string
Tags []Tag `gorm:"-"`
}
var jointItems []*jointItem
db.Raw(`SELECT
items.*,
(SELECT CONCAT(
'[',
GROUP_CONCAT(
JSON_OBJECT('id', id,
'name', name
)
),
']'
)) as parsed_tags
FROM items`).Scan(&jointItems)
for _, o := range jointItems {
var tempTags []Tag
if err := json.Unmarshall(o.ParsedTags, &tempTags) ; err != nil {
// do something
}
o.Tags = tempTags
}
編輯:代碼可能表現得很奇怪,所以我發現在移動時最好使用臨時標簽數組而不是使用相同的結構。

TA貢獻1851條經驗 獲得超5個贊
postgres 中的 sql:
create schema temp;
set search_path = temp;
create table item
(
id INT generated by default as identity primary key
);
create table tag
(
id INT generated by default as identity primary key,
name VARCHAR(160),
item_id INT references item (id)
);
create view item_tags as
select id,
(
select
array_to_json(array_agg(row_to_json(taglist.*))) as array_to_json
from (
select tag.name, tag.id
from tag
where item_id = item.id
) taglist ) as tags
from item ;
-- golang query this maybe
select row_to_json(row)
from (
select * from item_tags
) row;
然后golang查詢這個sql:
select row_to_json(row)
from (
select * from item_tags
) row;
并解組去結構:
親:
postgres 管理數據的關系。使用 sql 函數添加/更新數據。
golang 管理業務模型和邏輯。
這很簡單。
- 2 回答
- 0 關注
- 236 瀏覽
添加回答
舉報