Hi, i’m trying to insert data in a table using Yii’s AR model. I was wondering what is the equivalent method for MySQL’s ON DUPLICATE KEY UPDATE command in Yii’s AR.
Here is the method sample which inserts data from a huge xml feed.
public function insertData($name, $category, $brand, $price_unit, $weight_unit, $providers, $review_text, $flavor, $imageurl) {
$this->productModel = new Products;
$this->brandModel = new Brand;
$this->brandModel->name = $brand;
$this->brandModel->save();
$this->productModel->name = $name;
$this->productModel->category = $category;
$this->productModel->brand = $brand;
$this->productModel->weight_unit = $weight_unit;
$this->productModel->price_unit = $price_unit;
$this->productModel->flavors = $flavor;
$this->productModel->providers = $providers;
$this->productModel->review_text = $review_text;
$this->productModel->image_path = $imageurl;
$this->productModel->save();
}
As you can see i’m doing a simple insertion using save(). But i would like to implement the ON DUPLICATE KEY command of mysql.
Here is the table in question:
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | YES | MUL | NULL | |
| category | varchar(50) | YES | MUL | NULL | |
| brand | varchar(50) | NO | MUL | NULL | |
| weight | decimal(10,2) | YES | | NULL | |
| weight_unit | varchar(30) | YES | | NULL | |
| price | decimal(15,2) | YES | | NULL | |
| price_unit | varchar(30) | YES | | NULL | |
| flavors | varchar(45) | YES | | NULL | |
| providers | varchar(45) | YES | MUL | NULL | |
| review_text | text | YES | | NULL | |
| image_path | varchar(100) | YES | | NULL | |
+-------------+---------------+------+-----+---------+----------------+
So, id is the primary key here, name has a index set on it for faster lookups. Category and brand are foreign keys.
The query which i want to replicate using Yii’s ar would be something like this ::
INSERT INTO tbl_products (name, category, brand, weight_unit, price_unit, flavors, providers, review_text, image_path) values ('.$this->parseXML[0] .', '.
$this->parseXML[1] .','
.$this->parseXML[2] .','
. $this->parseXML[3] .','
. $this->parseXML[4] .','
. $this->parseXML[5] .','
.$this->parseXML[6] .','
.$this->parseXML[7] .','
.$this->parseXML[8].')
ON DUPLICATE KEY UPDATE
name = '.$this->parseXML[1].',
category = '.$this->parseXML[2].',
brand = '.$this->parseXML[3].'
So, what i the efficient method to do this using Yii’s AR. I’m trying to avoid using brute force methods, as much as i can.
Thanks, in advance.I would really appreciate any help that i can get on this.
thanks,
Maxx