我有一张演员表和一张电影表。我想添加一种可能性来找出“其他演员有哪些特定演员主演以及出演哪些电影”这个问题的答案。示例:“马克·哈米尔 (Mark Hamill) 与哈里森·福特 (Harrison Ford) 一起主演了《星球大战》”。
我正在创建“actor_partners”表作为连接表,它存储:
但是我正在努力解决这个问题 - 因为马克·哈米尔的 id 可能是 actor1 或 actor2。此外,使用以下架构和模型不起作用:它给出以下错误:
An error occurred when inspecting the object: #<ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'actor_partners.actor_id' in 'where clause'>
Actor Load (1.1ms) SELECT `actors`.* FROM `actors` INNER JOIN `actor_partners` ON `actors`.`id` = `actor_partners`.`actor1_id` WHERE `actor_partners`.`actor_id` = 3 /* loading for inspect */ LIMIT 11
架构.db
# ... lots of other stuff
create_table "actor_partners", charset: "utf8mb4", collation: "utf8mb4_general_ci", force: :cascade do |t|
t.bigint "actor1_id", null: false
t.bigint "actor2_id", null: false
t.string "movie_type", null: false
t.bigint "movie_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["actor1_id", "actor2_id", "movie_id"], name: "index_actor_partners_on_actor1_id_and_actor2_id_and_movie_id", unique: true
t.index ["actor1_id"], name: "index_actor_partners_on_actor1_id"
t.index ["actor2_id"], name: "index_actor_partners_on_actor2_id"
t.index ["movie_id"], name: "index_actor_partners_on_movie_id"
end
add_foreign_key "actor_partners", "actors", column: "actor1_id"
add_foreign_key "actor_partners", "actors", column: "actor2_id"
add_foreign_key "actor_partners", "movies"
actor_partner.rb
class ActorPartner < ApplicationRecord
belongs_to :actor1, class_name: 'Actor'
belongs_to :actor2, class_name: 'Actor'
belongs_to :movie
validates :movie_type, presence: true
end
演员.rb
class Actor < ApplicationRecord
# ... lots of other relationsships and stuff
has_many :actor_partners, dependent: :destroy
has_many :a_partners, through: :actor_partners, source: :actor1
has_many :b_partners, through: :actor_partners, source: :actor2
end
无论您如何执行此操作,在读取时都将是一项非常繁重的工作,但这都是写入后的静态数据。我认为在写入时将这些数据预先缓存在
actors
表中是一个更好的主意,这样您的读取就简单/快速。我假设您同时写一部电影及其所有演员。
很容易在您的
actors
表中有一个 JSONB 字段,用于存储“costars”的哈希值,其中其他演员的 id
是键(以避免重复),只需在将新电影写入时更新即可你的数据库。
显然,您现在需要回填来处理它,但即使这样也不会太难,因为您可以轻松地批量循环遍历您的
movies
表。