我有两张桌子:
1.广告客户帐户

create table if not exists advertiser_accounts (
   advertiser_id int(11) not null,
   deal_type_id int(11) not null,
   primary key (advertiser_id),
   CONSTRAINT account_advertiser_refs FOREIGN KEY (advertiser_id) REFERENCES advertisers (ap_advertiser_id ),
  CONSTRAINT deal_types_refs FOREIGN KEY (deal_type_id) REFERENCES  deal_types (id)
);

2.广告商
Advertiser(id: integer, ap_advertiser_id: integer)

在模型中:
广告客户帐户
class AdvertiserAccount < ActiveRecord::Base
 belong_to :advertiser
end

广告商
class Advertiser < ActiveRecord::Base
 has_one :advertiser_account
end

我想将广告客户帐户中的广告客户id与广告客户表中的广告客户id映射
在控制台上:AdvertiserAccount.first.advertiser
广告客户帐户负载(0.2ms)选择advertiser_accounts*fromadvertiser_accountsorder byadvertiser_accountsadvertiser_idasc limit 1
广告客户负载(0.2ms)从advertisers中选择advertisers*,其中advertisersid=153371限制1
结果我一无所获
但是,我想要这样的查询:
广告客户帐户负载(0.2ms)选择advertiser_accounts*fromadvertiser_accountsorder byadvertiser_accountsadvertiser_idasc limit 1
广告客户负载(0.2ms)从advertisers中选择advertisers*,其中advertisersap_advertiser_id=153371限制1

最佳答案

是否检查了ap_advertiser_id是否具有唯一键约束或主键约束(如果没有)。
您正在打破配置原则上的约定,所以必须在模型中显式指定主键和外键。
尝试将模型更改为-

class AdvertiserAccount < ActiveRecord::Base
  belong_to :advertiser, :foreign_key => :ap_advertiser_id,  :primary_key => :advertiser_id
end

class Advertiser < ActiveRecord::Base
   has_one :advertiser_account,  :primary_key => :ap_advertiser_id, :foreign_key => :advertiser_id
end

关于mysql - 当ID以外的外键时关联不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31544383/

10-11 02:48