我有一个客户模型,一个商人模型和一个交易模型。客户可以与商家进行交易,商人也可以与客户进行交易。最后,我想提出这样的疑问:
那么,从概念上讲,我应该如何为这些模型创建关联呢?像客户has_many :商人,通过::事务(反之亦然)?还是使用多态关联?等。
非常感谢你的帮助!
发布于 2014-08-02 01:03:29
从概念上讲,事务模型连接了客户和商人,因此:
class Customer < ActiveRecord::Base
has_many :transations
has_many :merchants, through: :transactions
end
class Merchant < ActiveRecord::Base
has_many :transactions
has_many :customers, through: :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :customer
belongs_to :merchant
end要查找客户的所有交易:
customer.transactions找出商人的所有交易:
merchant.transactions找到所有的客户#1的交易为商人#25
customer = Customer.find(1)
customer.transactions.where(merchant_id: 25)找到所有的商人1号的交易为客户#8
merchant = Merchant.find(1)
merchant.transactions.where(customer_id: 8)通过标记查找所有事务(假设标记是字符串字段):
transactions = Transaction.where(tag: 'best-seller')找到所有交易标记为“畅销书”的商人:
merchants = Merchant.includes(:transaction).where(transaction: {tag: 'best-seller'})找到所有带有“畅销书”标签的客户:
customers = Customer.includes(:transation).where(transaction: {tag: 'best-seller'})发布于 2014-08-02 05:17:22
好的,“注入”的建议看起来很棒。以下是ActiveJDBC中的相同内容
首先定义模型:
public class Customer extends Model {}
public class Merchant extends Model {}
public class Transaction extends Model {}第二,创建表:
顾客:
id | first_name | last_name | etc商人:
id | name | address1 | etc交易:
id | customer_id | merchant_id | tag | etc查找客户的所有事务:
customer.getAll(Transaction.class);找出商人的所有交易:
merchant.getAll(Transaction.class);找到所有的客户#1的交易为商人#25
customer = Customer.findById(1);
customer.get(Transaction.class, "merchant_id = ?", 25);找到所有的商人1号的交易为客户#8
merchant = Merchant.findById(1);
merchant.get(Transaction.class, "customer_id = ?", 8);通过标记查找所有事务(假设标记是字符串字段):
transactions = Transaction.where("tag = ?", "best-seller");找到所有交易标记为“畅销书”的商人:
transactions = Transaction.where("tag = 'best-seller'").include(Merchant.class);
//iterate over transactions, and get a merchants:
transactions.get(i).getAll(Merchant.class)这种方法只运行2个SQL查询,而且运行速度非常快。
我希望这能帮到你
https://stackoverflow.com/questions/25090554
复制相似问题