How to make multiple UPSERT in Yii2? - mysql

I am using Yii2 advance template. I have to insert 1000 to 2000 records in MySql Database.
Is it possible to make Multiple UPSERT Query in Yii2.
Please help me with your suggestion/answers. Thank you.

Since version 2.0.14 you have upsert() available.
Your code could look something like this:
$insertValues = [
'timestamp' => gmdate('YmdH'),
'entry_id' => $this->id,
'view_count' => 1,
];
$updateValues = ['view_count' => new \yii\db\Expression('table_name.view_count + 1')];
Yii::$app->db->createCommand()->upsert('table_name', $insertValues, $updateValues)->execute();
You can find the full documentation here: https://www.yiiframework.com/doc/api/2.0/yii-db-command#upsert()-detail

Try with modified batchInsert() method:
$db = \Yii::$app->db;
$sql = $db->queryBuilder->batchInsert($table, $fields, $rows);
$db->createCommand($sql . ' ON DUPLICATE KEY UPDATE')->execute();

Related

Add a prefix to values when using a yii\db\Query

Is there a way to add a prefix to values when using a DB query to get the data from a database? I have used a var as example to show you how I want it to be.
$query = (new \yii\db\Query())->select(['name' , 'product_image."$prefix"' ])->from('products');
Lets say that I want to add after every image path a prefix like _250x250, so the final output will be pathToImage_250x250 or uploads/pathToImage_250x250.
You may use yii\db\Expression to create more advanced selects. For example for MySQL you may use CONCAT() function for this:
$query = (new \yii\db\Query())
->select([
'name',
'product_image' => \yii\db\Expression('CONCAT(product_image, :suffix)', [
':suffix' => '_250x250',
]),
])
->from('products');

print last executed query in controller cakephp 3

suppose i have a query in cakephp 3
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
I want to print it like plain mysql query for example
SELECT * FROM posts....
can anyone please explain this how can i achieve this. Please answer it only in cakephp 3 environment. Is it possible to print it in controller as normal mysql query ? please do not mention queries.log file solution. beacause it is time taking to open file and see the query after every executed query in queries.log file in that is look in cakephp style
Thanks
In Controller, We need to write two lines after query code as follows
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
echo "<pre>";
print_r(debug($post));die;
It will show all result along with sql query syntax.
Here we are using debug for show result along with sql query.
Query:
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
For Print/Get SQL Statement of above query you can use debug() function as follow in controller:
$post = $this->Posts->get($id, [
'contain' => ['Postmeta']
]);
debug($post);
Just write:
die(print_r($post));

Delete multiple rows in YII2

I have an array of objects fetched from database:
$masterListContacts = MasterListContacts::find()
->select('master_list_contacts.*')
->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`')
->with('masterContact')
->where(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug])
->all();
Under certain circumstances, I need to delete all rows from the database represented in this array. But with both delete() and deleteAll() methods I got an error Call to a member function ... on array. Could someone tell me please which one is the best way to accomplish this?
UPDATE:
Here is my database structure.
Found better solution:
\Yii::$app
->db
->createCommand()
->delete('master_contacts', ['id' => $deletableMasterContacts])
->execute();
Where $deletableMasterContacts is array of master_contacts ids, which should be deleted
You can painlessly remove ->select('master_list_contacts.*').
->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`')
performs the same work that ->joinWith('masterContact').
For delete entites try use this code:
MasterListContacts::deleteAll(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug]);

Novice: How to do update with id in cakephp2 mysql?

I'm new to cakephp2 and mysql and I want to create a mysql query to update the data with a id that has been passed in.I'm a very slow learner so I would want some help.
$this->User->updateAll(
array(
'User.checked_count' => '`User`.`checked_count` + 1',
'User.modified' => "'" . date('Y-m-d H:i:s') . "'"
),
array(
'User.username' => $username,
)
);
PS. How to get the results from the query above and use foreach loop? It doesn't work, so Im having a little trouble with it .
In cakePhp 2.x you can do it like that:
1) Below is simple update using save() function, where you pass id as reference and cake automatically updates the table when id is set else will insert the data in new row:
$this->User->id = $Id;
$this->User->save($this->request->data);
2) If you want one or more records in a single call to get updated use updateAll() function:
$this->User->updateAll(
array('User.checked_count' => $count),
array('User.id ' => $userId)
);
Try this code
$this->User->id = $passedId;
$this->User->save($this->data);
In above code If user_id is present then It update user data other wise it save userData.

Trouble insert date form to mysql in drupal 7

hi im having little trouble at inserting date from drupal to mysql
here the code that i'm trying
.....
$form['kotak']['tgl'] = array(
'#type' => 'date',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
everytime i'm submit, error code like this
db_insert failed. Message = SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1, query= INSERT INTO {jp_1} (tanggal) VALUES (:db_insert_placeholder_0_month, :db_insert_placeholder_0_day, :db_insert_placeholder_0_year)
any suggestion or correction?
From the mysql error it looks like the table you created has required fields (a columns Null property is set to 0, which means that there must be a value for tha column for every row you want to insert)
Check whether there are any columns which have null set to 0.
From your example I can't see what you're trying to achieve, but in many cases it's not necessary to write into db tables manually (using db_insert()) as you can get the same result easier by creating a content type (node type) which handles a lot of functionality for you.
I hope that helps, Martin
i'm finally managed to find the answer, all i need is download "Date" module and activate its "Date API". Here the code
.....
$datex = '2005-1-1';
$format = 'Y-m-d';
$form['kotak']['tgl'] = array(
'#type' => 'date_select',
'#default_value' => $datex,
'#date_format' => $format,
'#date_year_range' => '-10:+30',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
and now i have no problem delivering to mysql.
Hope that will help other drupal newbie developer like me. Thanks :D