Actually, Jeremy, one more question if you don't mind: in this example, suppose you have the Order and you want to get the Products along with the join. Would it be possible to get the OrderProduct representation along with the Product, or do you have to write a separate set of queries for that (e.g. OrderProduct.where(...))?
On Monday, June 12, 2017 at 7:57:15 PM UTC-4, Greg Gilbert wrote: > > Much appreciated. Thanks! > > On Monday, June 12, 2017 at 10:02:16 AM UTC-4, Jeremy Evans wrote: >> >> On Sunday, June 11, 2017 at 9:04:14 PM UTC-7, Greg Gilbert wrote: >>> >>> There have been a few posts over the years about this, but I was >>> wondering what the latest and greatest approach is. >>> >>> Suppose you have Orders and Products, and a purchase is done in a join >>> table called :orders_products. The join table has another field, >>> 'quantity', indicating how many of the Products were in the Order. How >>> would you store, and also query and return the value of, :quantity? >>> >>> class Order < Sequel::Model >>> many_to_many :products, through: :order_product >>> end >>> >>> class Product < Sequel::Model >>> many_to_many :orders, through: :order_product >>> end >>> >>> class OrderProduct < Sequel::Model(:orders_products) >>> many_to_one :order >>> many_to_one :product >>> Integer :quantity >>> end >>> >>> I believe this is correct so far. Here are my questions: >>> >>> >>> 1. Rather than using order.add_product, you'd do something like >>> OrderProduct.new(order: >>> order, product: product, quantity: 23). Is that still the best way >>> to do this, or is there a better way? >>> >>> Using OrderProduct.new would be a better way. >> >> >>> >>> 1. When getting order.products, how would you also get the quantity? >>> >>> Use the :select=>[Sequel[:products].*, >> Sequel[:orders_products][:quantity]] association option >> >> >>> >>> 1. How would you update the value of quantity in the join table for >>> an Order that already exists? >>> >>> DB[:orders_products].where(:order_id=>order_id, >> :product_id=>product_id).update(:quantity=>quantity) >> >> >>> >>> 1. I saw references to the dataset_associations plugin and some >>> others. How would those work here? >>> >>> As they usually do, I don't think there's anything special related to >> this circumstance. >> >> Thanks, >> Jeremy >> > -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/sequel-talk. For more options, visit https://groups.google.com/d/optout.
