【发布时间】:2018-07-30 14:58:24
【问题描述】:
我的数据库中有这些表,Locations 和 Services
每个Location 记录都有一个名为location_ids 的属性,它是一个以逗号分隔的id 列表*。
*我这样表示我的多对多关系,因为我有很多类似于Services 的表,并且不想拥有大量的链接表
我的桌子
CREATE TABLE services (
id bigint(20) UNSIGNED NOT NULL,
location_ids varchar(255) DEFAULT NULL,
image varchar(255) DEFAULT NULL,
created_at timestamp NULL DEFAULT NULL,
created_by bigint(20) UNSIGNED NOT NULL DEFAULT '0',
updated_at timestamp NULL DEFAULT NULL,
updated_by bigint(20) UNSIGNED DEFAULT NULL
);
CREATE TABLE locations (
id bigint(20) UNSIGNED NOT NULL,
street1 varchar(255) DEFAULT NULL,
street2 varchar(255) DEFAULT NULL,
city varchar(255) DEFAULT NULL,
province varchar(255) DEFAULT NULL,
country varchar(255) DEFAULT NULL,
postal_code varchar(255) DEFAULT NULL,
phone1 varchar(45) DEFAULT NULL,
phone2 varchar(45) DEFAULT NULL,
fax varchar(255) DEFAULT NULL,
email varchar(255) DEFAULT NULL,
twitter_url varchar(255) DEFAULT NULL,
facebook_url varchar(255) DEFAULT NULL,
created_at timestamp NULL DEFAULT NULL,
created_by bigint(20) UNSIGNED NOT NULL DEFAULT '0',
updated_at timestamp NULL DEFAULT NULL,
updated_by bigint(20) UNSIGNED DEFAULT NULL
);
我正在尝试检索所有Services,其中特定位置的ID(我从我的参数中获得)在location_ids 属性中。
这是我的查询(不起作用),它可能会使我试图检索的内容更清楚
Admin::Service.where("#{params[:location_id]} in (services.location_ids)")
*params[:location_id] 将是当前位置的 id
任何帮助将不胜感激!
更新
我结束在我的数据库中添加 5 个链接表,通过 Rails 使其更容易和更易于访问。 感谢所有帮助过的人
【问题讨论】:
-
看起来服务没有名为 location ids 的列,它的位置 id
-
这实际上是一种抱歉,我已修复它
-
您基本上只能执行 SQL
LIKE查询来获取在location_id字符串中某处具有 id 的所有行。但我建议不要走这条路,原因有两个:1)会很慢,因为LIKE查询不能使用索引。 2) 您将不得不处理正在搜索 ID%123%找到具有location_id的记录的案例,如下所示:1234, 4567。我的建议是:不要与 Rails 约定冲突,使用常见的has_and_belongs_to关系。 -
这是否意味着为我的关系使用 link_tables 会更简单、更高效,即使这意味着拥有更多表?
-
是的,这会更容易实现(因为它遵循 Rails 约定)并且性能会更好!
标签: mysql ruby-on-rails ruby