0

我有一个客户模型、一个商家模型和一个交易模型。客户可以与商家进行交易,商家也可以与客户进行交易。最终,我想查询以下内容:

  1. 客户进行的所有交易
  2. 商家进行的所有交易
  3. 客户 X 与商家 Y 的所有交易(反之亦然)
  4. 可选:先完成所有带有特定标签的交易,然后找到与这些交易相关的所有关联商户和客户。这是一个很好的功能,但如果它太复杂而无法在答案中解释,那么不要担心

那么从概念上讲,我应该如何为每个模型创建关联?像客户 has_many :merchants 一样,通过: :transactions (反之亦然)?还是使用多态关联?等等等等

非常感谢你的帮助!!!

4

2 回答 2

2

好的,@infused 的建议看起来很棒。在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);

为客户 #8 查找商家 #1 的所有交易

 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 查询,而且速度非常快。

我希望这有帮助

于 2014-08-02T05:17:22.000 回答
1

从概念上讲,Transaction 模型将 Customer 和 Merchant 连接起来,因此:

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)

为客户 #8 查找商家 #1 的所有交易

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-02T01:03:29.143 回答