我用两个表简化了我的问题,分别是Coconut和Coconut_lists。椰子表存储椰子的规格,而椰子列表存储哪个卖方拥有椰子。每次都在卖方和椰子之间创建一个关系,将其插入到coconut_lists表中。
我试图通过带有属性的关键字来设置HasMany,HasOne,BelongsToMany的不同关系。
椰子列表
import { Column, DataType, Model, Table, ForeignKey, BelongsTo } from 'sequelize-typescript';
import Coconut from './coconut';
@Table({
modelName: 'cononuts_list',
timestamps: true,
paranoid: true,
})
export default class CoconutList extends Model<CoconutList> {
@Column({
allowNull: false,
primaryKey: true,
autoIncrement: true,
type: DataType.INTEGER,
})
public id: number;
@Column({
type: DataType.STRING,
allowNull: false,
})
public sellerId: string;
@ForeignKey(() => coconut)
@Column({
type: DataType.INTEGER,
allowNull: false,
})
public coconutId: number;
@BelongsTo(() => Coconut, 'coconutId')
public coconut: Coconut;
}
椰子
import { Column, DataType, Model, Table, HasMany } from 'sequelize-typescript';
import CoconutList from './coconutList';
@Table({
modelName: 'coconuts',
timestamps: true,
paranoid: true,
})
export default class Coconut extends Model<Coconut> {
@Column({
allowNull: false,
primaryKey: true,
autoIncrement: true,
type: DataType.INTEGER,
})
public id: number;
@HasMany(() => CoconutList, 'id')
public coconutList: CoconutList[];
@Column({
type: DataType.INTEGER,
allowNull: false,
})
public weight: number;
@Column({
type: DataType.INTEGER,
allowNull: false,
})
public count: number;
@Column({
type: DataType.FLOAT,
allowNull: false,
})
public size: number;
}
查询:
const coconutsBySeller = await CoconutList.findAll({
include: [
{
model: Coconut,
attributes: ['weight', 'size', 'count'],
},
],
attributes: ['sellerId'],
});
代码输出如下:
[
{
"sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
"coconut": {
"weight": 100,
"count": 6,
"size": 11,
}
},
{
"sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
"coconut": {
"weight": 200,
"count": 12,
"size": 20,
}
},
{
"sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
"coconut": {
"weight": 300,
"count": 18,
"size": 50,
}
},
{
"sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
"coconut": {
"weight": 100,
"count": 6,
"size": 11,
}
}
]
我想得到
[
{
"sellerId": "f3ff90d8-ed8e-42c9-9c7b-d607111a359e",
[{
"weight": 100,
"count": 6,
"size": 11,
},
{
"weight": 200,
"count": 12,
"size": 20,
}]
},
{
"sellerId": "ffffaaaa-ed8e-42c9-9c7b-d607111a359e",
[{
"weight": 300,
"count": 18,
"size": 50,
},
{
"weight": 100,
"count": 6,
"size": 11,
}
]
]
除了数据格式外,我还想知道是否有可能在上述查询中使用Sequelize获得分配给卖方的椰子的重量,数量,大小字段的min_max值。
答案 0 :(得分:0)
您可以尝试按卖方分组:
const coconutsBySeller = await CoconutList.findAll({
include: [
{
model: Coconut,
attributes: ['weight', 'size', 'count'],
},
],
attributes: ['sellerId'],
group: ['sellerId']
});