gpt4 book ai didi

mysql - 使用 JOIN 访问现有数据库的表

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:05 24 4
gpt4 key购买 nike

我在 MySQL 中有一个现有数据库,其中包含具有多对多 关系的表:

  1. 位置
  2. channel
  3. location_channel - JOIN 表。

我已经创建了模型:

class Location < ActiveRecord::Base
self.table_name = "location"
has_and_belongs_to_many :channels
end

class Channel < ActiveRecord::Base
self.table_name = "channel"
has_and_belongs_to_many :locations
end

在 Rails 控制台中,我能够分别访问每个表的记录,例如:Location.allChannel.all

但是当我尝试通过以下方式访问给定 location 的所有 channels 时:

location = Location.first
location.channels

报错:

Mysql2::Error: Table 'mydb.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'switchboard_2_api_poc.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`

或者:

Mysql2::Error: Table 'mydb.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'switchboard_2_api_poc.channel_location' doesn't exist: SHOW FULL FIELDS FROM `channel_location`

当我尝试时:

channel = Channel.first
channel.locations

我怀疑,我需要描述一个 JOINlocation_channel 以某种方式消除错误并打印正确的值。 p>

最佳答案

你需要告诉rails连接表的名称,因为它猜错了。

has_and_belongs_to_many :locations, join_table: 'location_channel'

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

关于mysql - 使用 JOIN 访问现有数据库的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32183310/

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