gpt4 book ai didi

mysql - 由于关系,DataMapper 无法删除记录

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:34 25 4
gpt4 key购买 nike

我有这个带有 Torrent 和 Tag 的很多 DataMapper/MySQL 设置,如下所示:

class Torrent
include DataMapper::Resource

property :id, Serial
property :name, String
property :magnet, Text
property :created_at, DateTime

has n, :tags, :through => Resource
end

class Tag
include DataMapper::Resource

property :id, Serial
property :name, String
property :hits, Integer

has n, :torrents, :through => Resource
end

然而,当试图通过 Torrent.first.destroy 或类似的东西销毁 torrent 时,DataMapper 返回 false

我尝试了直接的 SQL 查询,例如 delete from torrents where name like '%ubuntu%',由于 MySQL 错误 1451 而失败:

ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`brightswipe`.`tag_torrents`, CONSTRAINT `tag_torrents_torrent_fk` FOREIGN KEY (`torrent_id`) REFERENCES `torrents` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

我认为有一些 DataMapper 设置,因此在删除 torrent 时我可以:

  1. 删除标签关联
  2. 删除种子

删除标签时我可以:

  1. 从所有带有该标签的种子中删除标签关联
  2. 删除标签

我该怎么做?

最佳答案

尝试使用这个插件自动管理关系:

https://github.com/datamapper/dm-constraints

这将允许您销毁 M:M assocs,尽管您必须手动清理 assocs 表:

class Tag
...
has n, :torrents, :through => Resource, :constraint => :skip

class Torrent
...
has n, :tags, :through => Resource, :constraint => :skip

另一种选择是手动从 assocs 表中删除关系,然后您可以毫无问题地删除项目,因为您通过从 assocs 表中删除相应的条目来破坏关系。

基本示例:

tr = Torrent.create
tg = Tag.create

tr.tags << tg
tr.save

tg.torrents << tr
tg.save

# destroying relation

TagTorrent.first(:tag => tg, :torrent => tr).destroy!

# or
tr.tag_torrents(:tag => tg).destroy

# or
tg.tag_torrents(:torrent => tr).destroy

# destroy items

tr.destroy!
tg.destroy!

关于mysql - 由于关系,DataMapper 无法删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13144198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com