我的应用程序的功能之一是根据查询参数检查某人从何处访问了链接。
基于此,我有以下代码将点击记录在Clicks
表中;然后将外键设置为另一个表中的URL
;最后,我将外键设置为也在另一个表(Origins
)中的Origin。
如果我在单击和click.setUrl(url)
上使用url.setClick(click)
而不是 const urlCode = req.params.urlCode
const org = req.query.org
let err
try {
const url = await Urls.findOne({ where: { urlCode: urlCode } })
const origin = await Origins.findOne({ where: { abbr: org } })
if (url === null) {
res.redirect(`${process.env.WEB_URL}/not-found`)
err = { code: 404, msg: 'URL Not found' }
throw err
}
const click = await Clicks.create()
click.setOrigin(origin)
* url.setClick(click)
res.redirect(url.originalUrl)
} catch (err) {
console.log(err)
res.status(err.code).send(err.msg)
}
,则如果我使用belongsTo代替hasMany,一切都很好。
Executing (default): UPDATE `Clicks` SET `originId`=NULL,`updatedAt`='2019-06-10 11:05:16' WHERE `id` = 5
Executing (default): UPDATE `Clicks` SET `UrlId`=NULL,`updatedAt`='2019-06-10 11:05:16' WHERE `id` IN (4)
Executing (default): UPDATE `Clicks` SET `UrlId`=1,`updatedAt`='2019-06-10 11:05:16' WHERE `id` IN (5)
这是输出。最后两行与上面带有星号的标记行相关。
问题是在第二行,设置器将先前的ID重置为NULL。
module.exports = (sequelize, DataTypes) => {
const Urls = sequelize.define('Urls', {
originalUrl: {
type: DataTypes.STRING,
allowNull: false
},
shortUrl: { type: DataTypes.STRING },
urlCode: { type: DataTypes.STRING }
})
Urls.associate = function (models) {
Urls.hasMany(models.Clicks, { as: 'click' })
}
return Urls
}
module.exports = (sequelize, DataTypes) => {
const Clicks = sequelize.define('Clicks')
Clicks.associate = function (models) {
Clicks.belongsTo(models.Origins, { as: 'origin' })
}
return Clicks
}
module.exports = (sequelize, DataTypes) => {
const Origins = sequelize.define('Origins', {
origin: {
type: DataTypes.STRING
},
abbr: {
type: DataTypes.STRING
}
})
return Origins
}
import { FormGroup, ValidationErrors } from '@angular/forms';
export class ProfileCustomValidators {
static validateTime(fg: FormGroup): ValidationErrors {
const staffForm = fg.get('staffForm')
const fromTime = staffForm.get('fromTime').value;
const toTime = staffForm.get('toTime').value;
if(fromTime > toTime) {
return {
'endTime': {
message: 'End time should be greater than start time'
}
}
}
return null;
}
}
答案 0 :(得分:0)
解决了问题。
const click = await Clicks.create()
click.setOrigin(origin)
//- url.setClick(click)
+ url.addClick(click)
res.redirect(url.originalUrl)