sroes
sroes

Reputation: 15053

Insert into .. select from .. using zend db

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?

Upvotes: 4

Views: 8375

Answers (2)

rodrigo-silveira
rodrigo-silveira

Reputation: 13078

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
        )")
    )
);

Upvotes: 2

altern
altern

Reputation: 5949

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);
} 

Upvotes: 6

Related Questions