4

I have the following raw query which moves items from a shopping cart to an order table:

insert into webshop_order_item (
    order_id,
    product_id,
    count
)
select
    1,
    product_id,
    count
from 
    webshop_cart

I am using the Zend DB for all my modeling. I was wondering if there is a way of achieving the goal of the above query without having to use a raw query?

2 Answers 2

6

There is no way of inserting from select in zend db yet. However, if you need this feature only for one adapter, then you could use approach similar to given below:

public function insertSelect($tableName, Zend_Db_Select $select, array
$fields = array()) {
    $fieldString = '';
    if (count($fields))
    {
        foreach($fields as $fieldKey => $field)
        {
            $fields[$fieldKey] =  $this->quoteIdentifier($field);
        }

        $fieldString = ' (' . implode(',', $fields) . ')';
    }

    $query  = "INSERT INTO ".$this->quoteIdentifier($tableName) .
$fieldString . " ";
    $query .= $select;

    $this->_db->query($query);
} 
Sign up to request clarification or add additional context in comments.

Comments

2

This works fine for me: I use a Zend_Db_Expr. Sanitize as needed.

$this->db->insert("sa_article_attributes", array(
    "article_id" => $sid,
    "article_attribute_id" => new Zend_Db_Expr("(
        SELECT Attribute.id FROM sa_attributes Attribute
        WHERE Attribute.title = '{$category}'
        LIMIT 1
        )")
    )
);

1 Comment

This is not the same. The query from my question will insert multiple rows. Yours will only insert one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.