cross_product
left.cross_product(right)left.cross_product(right)// orleft.cross_join(right)Problem
Section titled “Problem”Find every combination of tuples from two relations.
Example: Given these sizes and these colors, what are all the different T-shirt variants?
Description
Section titled “Description”The cross product of two relations is produced by combining every tuple from the left relation with every tuple from the right relation.
The result’s heading contains all attributes from left plus all attributes from right.
Requirements
Section titled “Requirements”The headings of the two relations must not overlap, ie they can have no attributes with the same names.
Example
Section titled “Example”models = Bmg::Relation.new([ { style: "slim", color: "red" }, { style: "slim", color: "blue" }, { style: "loose", color: "red" },])
sizes = Bmg::Relation.new([ { size: "S" }, { size: "M" }, { size: "L" }])
t_shirts = models.cross_product(sizes)
t_shirts.to_a
=> [{:size=>"S", :style=>"slim", :color=>"red"}, {:size=>"M", :style=>"slim", :color=>"red"}, {:size=>"L", :style=>"slim", :color=>"red"}, {:size=>"S", :style=>"slim", :color=>"blue"}, {:size=>"M", :style=>"slim", :color=>"blue"}, {:size=>"L", :style=>"slim", :color=>"blue"}, {:size=>"S", :style=>"loose", :color=>"red"}, {:size=>"M", :style=>"loose", :color=>"red"}, {:size=>"L", :style=>"loose", :color=>"red"}]Generated SQL
Section titled “Generated SQL”SELECT `t1`.`style`, `t1`.`color`, `t2`.`size`FROM `models` AS 't1'CROSS JOIN `sizes` AS 't2'const models = Bmg([ { style: "slim", color: "red" }, { style: "slim", color: "blue" }, { style: "loose", color: "red" },])
const sizes = Bmg([ { size: "S" }, { size: "M" }, { size: "L" }])
const tShirts = models.cross_product(sizes)
tShirts.toArray()
// => [{ size: "S", style: "slim", color: "red" },// { size: "M", style: "slim", color: "red" },// { size: "L", style: "slim", color: "red" },// { size: "S", style: "slim", color: "blue" },// { size: "M", style: "slim", color: "blue" },// { size: "L", style: "slim", color: "blue" },// { size: "S", style: "loose", color: "red" },// { size: "M", style: "loose", color: "red" },// { size: "L", style: "loose", color: "red" }]