【发布时间】:2019-11-05 17:02:58
【问题描述】:
我来了
"从 "id" = $1 的 "images" 中删除 - 更新或删除表 “图像”违反外键约束“cmets_image_id_foreign” 在“cmets”表上
删除具有 cmets 的图像(或为了更容易解释的帖子对象)时。
我正在使用 Knex 和书架
并使用
我认为我的设置正确。
书架
import knex from 'knex';
import bookshelf from 'bookshelf';
import config from '../knexfile';
import cascadeDelete from 'bookshelf-cascade-delete';
const herokuOrNot = process.env.NODE_ENV !== 'production' ? config.development : config.production
const Bookshelf = bookshelf(knex(herokuOrNot));
Bookshelf.plugin('registry');
Bookshelf.plugin(cascadeDelete);
export default Bookshelf;
Image.js
import bookshelf from '../config/bookshelf';
import User from './User';
import Comment from './Comment';
const Image = bookshelf.Model.extend({
tableName: 'images',
timestamps: false,
user(){
return this.belongsTo(User);
},
dependents: ['comments'],
comments(){
return this.hasMany(Comment)
}
});
这就是它被删除的方式。
图片删除路线
router.post('/delete/:id', (req, res) => {
const id = req.params.id;
Image.forge({id:id}).fetch().then( (image) =>{
return image.destroy().then( () => {
return res.json({error: true, data: {message: 'Image Deleted'}})
}).catch( (err) => {
return res.status(500).json({error: true, data: {message:err.message}});
})
})
.catch(function (err) {
return res.status(500).json({error: true, data: {message: err.message}});
});
})
图片表格
export const up = async knex => {
await knex.schema.createTable('images', (t) => {
t.increments('id').primary().unsigned();
t.string('image_title', 40);
t.string('img_url', 250 );
t.timestamp('created_at').defaultTo(knex.fn.now());
t.timestamp('updated_at').defaultTo(knex.fn.now());
t.integer('user_id').unsigned().references('id').inTable('users');
})
};
export const down = async knex => {
await knex.schema.dropTable("images");
};
cmets 表
export const up = async knex => {
await knex.schema.createTable('comments', (t) => {
t.increments('id').primary().unsigned();
t.string('comment_body', 500);
t.timestamp('created_at').defaultTo(knex.fn.now());
t.timestamp('updated_at').defaultTo(knex.fn.now());
t.integer('user_id').unsigned().references('id').inTable('users');
t.integer('image_id').unsigned().references('id').inTable('images');
})
};
export const down = async knex => {
await knex.schema.dropTable("comments");
};
【问题讨论】:
-
我修好了。这是解决方案
标签: postgresql knex.js bookshelf.js