2

次のように、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または同様の方法で、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セットアップがあると思います:

  1. タグの関連付けを削除します
  2. トレントを削除する

タグを削除するときは、次のことができます。

  1. そのタグを持つすべての torrent からタグの関連付けを削除します
  2. タグを削除する

これについてどうすればいいですか?

4

1 に答える 1

4

このプラグインを使用して、リレーションを自動的に管理してみてください:

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 テーブルからリレーションを手動で削除することです。その後、関連テーブルから対応するエントリを削除してリレーションを破棄したため、問題なくアイテムを削除できます。

基本的な例:

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!
于 2012-10-30T17:11:09.823 に答える