Dylan Glockler Tue Jan 22 21:20:57 -0500 2013

Subject: Best way to add multiple records to create ties in a relational DB

I'm fairly new to ActiveRecord and I've searched and can't seem to find an answer to this. I have created a products table, loaded up my products and when and order is submitted, I create the order record and I want to add a series of records in a order_products table, so if the user purchases six items, six records are added to order_products linking the order to the products purchased.

I add the order, get the new ID back, but how can I then iterate through the product ids (posted from my cart through a form post) and add a record for each?

Eventually I scripted my own SQL but I can't seem to figure out the syntax for running a raw query either.

class order extends ActiveRecord\Model
$order = new Order();
$newId = $order->id;
class order_product extends ActiveRecord\Model
$orderid = $_POST['order_items'];
$strIns = 'INSERT INTO order_products (product_id, order_id) VALUES ';
$arrItems = explode(",",$orderid);
$endKey = key($arrItems);
while (list($key, $val) = each($arrItems)) {
$strIns = $strIns . '('.$val.', '.$newId.')';
if ($key == $endKey) {
$strIns = $strIns . ';';
} else {
$strIns = $strIns . ',';
//$order_product = new order_product();
$productsOrdered = order_product::query($strIns);