php yii2 how to make automaticly id in query yii2 insert? - php

i have a code like this ,
$request = Yii::$app->request;
$post = $request->post();
$filesettingid = $post['filesettingid'];
$checkboxValue = $post['selection'];
for($i=0;$i<sizeof($checkboxValue);$i++) {
$store = Yii::$app->db->createCommand('SELECT id FROM store WHERE port='.$checkboxValue[$i])->queryAll();
$storeid = $store[$i]['id'];
Yii::$app->db->createCommand()->insert('tes',
[
'id' => $i+1,
'filesetting_id' => $filesettingid,
'store_id' => $storeid
])->execute();
}
what i want is, each i insert the new data, id will generate automaticly like 1,2,3,4.
the problem in above code is, the ID always be 1.
is it possible to make it real?
so what i want is :
First time insert, id = 1, second is id = 2 , and that is happen automatically.

Have you considered setting database engine to auto increment values with each insert?
Take as an example Yii2 default user table. ID filed is auto incremented, and you don't have to worry about setting it problematically. Every time you send a new insert engine increments ID filed by itself.
See default migration under "advanced template"\console\migrations\m130524_201442_int. (your file name might be different depending on the Yii2 version)
$this->createTable('{{%user}}', [
'id' => $this->primaryKey(),
'username' => $this->string()->notNull()->unique(),
'auth_key' => $this->string(32)->notNull(),
'password_hash' => $this->string()->notNull(),
'password_reset_token' => $this->string()->unique(),
'email' => $this->string()->notNull()->unique(),
'status' => $this->smallInteger()->notNull()->defaultValue(0),
.........
], $tableOptions);
When setting 'id' to primary key database automatically knows to auto increment it. If you already have a table the ID field is not primary key you can use the followign migration:
$this->alterColumn('{{%databaseName}}', 'columnName', $this->integer()->notNull().' AUTO_INCREMENT');
You can also set it from management console, or run a SQL query. Depending on database engine you are using this might look a little different but the concept is the same.
MYSQL:
In MySQL workbench right click on table in question, select Alter Table and check NNm and AI next to column you want auto increment. See Screenshot
Or run command:
ALTER TABLE `dbName`.`nameOfTheTable` MODIFY `columnName` INT AUTO_INCREMENT NOT NULL;
I am a bit rusty on my SQL, so if it does not work let me know I will get you right command.
Hope this helps. Good luck.

Related

Laravel update specific column in database 'cost' and add supplier_id to another database table

i'm working with sensitive data hope you can help find if there any wrong in code's writing
i have list of suppliers in my database i added column 'cost'
i'm trying to update and insert cost for existing suppliers from specific query
and i created model and migration to get foreign keys too by adding the puled supplier id from the query
....
$suppliers_data = $suppliers_query->fetchall(PDO::FETCH_ASSOC);
foreach ($suppliers_data as $supplier_data) {
$supplier_name = $supplier_data['supplier_name'];
$cost_rate = $supplier_data['Cost'];
if (!Supplier::where('supplier', $supplier_name)->exists()) {
Supplier::insert([
'supplier' => $supplier_name,
'cost_rate' => $cost_rate
]);
} else {
Supplier::update([
'cost_rate' => $cost_rate // does this will update cost for the current supplier ?
]);
}
$supplier_id = Supplier::where('supplier', $supplier_name)->pluck('supplier_id');
Test::insert($supplier_id);
}
$supplier_count = test::count();
Test::update(['test_data_count' => $supplier_count]);
Updating table data with supplier name is not correct here I believe. Instead of using supplier name in where condition using particular supplier id is recommended for better application. Names can be duplicate so its not a good idea to use supplier name in where.
In your current code I have 2 things to say :
You need to add where in update eloquent to work properly
Supplier::where('supplier', $supplier_name)
->update([
'cost_rate' => $cost_rate // this will update cost for the current supplier
]);
Or to minimalize the code you can use updateorCreate method instead of making insert and update in the if() else() condition
Supplier::updateOrCreate(
['supplier' => $supplier_name],
['cost_rate' => $cost_rate]
);

Laravel Eloquent - bulk update with whereIn array

I'm working on a project where I need to update many rows at once per coin Id.
in order to update all coins values, Im getting them all from the API, so for example I have back:
$coinsList= [[id="bitcoin", symbol="btc", name="Bintcoin"],[id="etherium", symbol="eth", name="Etherium"]];
and the database table columns is the following:
**| id | coin_id | symbol | name |**
now, I want to update all values to the database, according to the id only, so this is what I did:
// first get ids from my table
$exist_ids = Coinlist::all('coin_id')->pluck('coin_id')->toArray();
//get all ids to update (to ignore other ids):
$updatable_ids = array_values(array_intersect($exist_ids, $allCoinIds));//result for example is: array("bitcoin","etherium");
//and now, update the database:
Coinlist::whereIn('coin_id', $updatable_ids)
->update([
'symbol' => $coinsList[$key]['symbol'],
'name' => $coinsList[$key]['name'],
'updated_at' => now()
]);
the problem is, I don't have the "$key" in order to update the right row, what am I missing here?
Thanks!
Here is a good way to solve it:
in the beginning, I used this library: https://github.com/mavinoo/laravelBatch
to update many dynamic rows, but it was really slow, then thanks to Yasin, I moved to: https://github.com/iksaku/laravel-mass-update and now it works way better.
the implementation is simple, add a simple code to the Model class, then add:
User::massUpdate(
values: [
['username' => 'iksaku', 'name' => 'Jorge González'],
['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
],
uniqueBy: 'username'
);
while uniqueBy is the key for the row, and add other columns values to change them dynamically.

How to add auto increment in field of SuiteCRM

I am using SuiteCRM-7.11.5 on Windows. I want to create an ID Label which shows itself auto incremented in the the "Create New Task" window. If showing auto incremented is not possible I at least want it to auto increment in the mySQL database.
I've found some question in Stack Overflow and on SuiteCRM forum (No Extension folder) which are all outdated or didn't work at all. The plugins are removed from github. Any help, hack or work around is appreciated. I am also new to suitecrm and mysql so step by step answer would be appreciated.
I also tried adding auto increment option in phpmyadmin but it throw error as
Incorrect column specifier for column 'id'
Auto Increment is definitely possible in suiteCRM, all you need to put a field using code like this.
'auto_number' =>
array(
'name' => 'auto_number',
'vname' => 'Serial No',
'type' => 'int',
'len' => 11,
'required'=>true,
'auto_increment' => true,
),
Create int type field and create before save logic hook. Add below code,
global $db;
$query = "SELECT MAX(field_name) as max_count FROM table where deleted=0";
$result = $db->query($query);
$row = $db->fetchByAssoc($result);
$max_number = $row['max_count'];
if(empty($max_number)){
$max_number = 1;
}
else{
(int)$max_ticket_number++;
}
if(empty($bean->field_name)){
$bean->field_name = $max_ticket_number;
}
}

Laravel update Issue

Here is my code -
$updatecompany = DB::table('Companies')
->where('ID', (int)$companyid)
->update(array(
'CompanyName' => $companyname,
'CompanyAddress' => $companyaddress,
'CompanyEmail' => $companyemail,
'ContactName' => $contactname,
'CompanyCity' => $companycity,
'CompanyState' => $companystate,
'CompanyZip' => $companyzipcode,
'CompanyPhone' => $companyphone,
));
$updatecompany is always 0. What might be the problem?
One of most possible reasons is that you are updating with the same data in the database.
There needs one out of the box solution, of course if you can do it.
So, no rows are updating, even if the SQL is correct.
Here is my suggestion:
Add a new column updatedOn in DB Table Companies.
The type should be TIMESTAMP and add attribute ON UPDATE CURRENT_TIMESTAMP.
This way you will always get row affected and hence you get return value other than 0.
You don't need to cast $companyId to an integer there. It does not help Laravel's query builder.
Use dd($companyId) and dump the variable before you run the query and find out what it is.

CakePHP - Why does Model::save cause() an INSERT instead of an UPDATE?

I want to update database in CAKEPHP's Way
this is my controller
$data = array(
'KnowledgeBase' => array(
'kb_title' => $this->data['KnowledgeBase']['kb_title'],
'kb_content' => $this->data['KnowledgeBase']['kb_content']
'kb_last_update' => date("Y-m-d G:i:s"),
'kb_segment' => $this->data['KnowledgeBase']['kb_segment']
));
$this->KnowledgeBase->id_kb = $this->data['KnowledgeBase']['id_kb'];
$this->KnowledgeBase->save($data);
assume I have post form is true, when I execute the program
I have some error like this :
Database Error
Error: SQLSTATE[23000]: [Microsoft][SQL Server Native Client 10.0]
[SQL Server]Violation of PRIMARY KEY constraint 'PK_cnaf_kb'.
Cannot insert duplicate key in object 'dbo.cnaf_kb'.
SQL Query: INSERT INTO [cnaf_kb] ([kb_judul], [kb_segment], [kb_isi], [id_kb], [kb_last_update], [kb_status]) VALUES (N'HARRIS TEST 4 ', N'4', N'<p>TESSSSSSSSSSSSSSSSSSSSSS</p> ', 73,
'2013-10-04 16:57:00', 1)
why the function use the insert query? not update ?
note : im not using form helper for post to controller, and I use Cakephp 2.3.8 version and sql server 2008 for database
Im sorry for my bad english, I hope someone can help me :(((
You do not supply a primary key value, that's why.
No matter what your primary key is named (Model::$primaryKey), on the model object you have to use the id property (Model::$id) if you want to set the primary key value.
$this->KnowledgeBase->id = $this->data['KnowledgeBase']['id_kb'];
Internally the model maps this to the appropriate primary key field.
In the data however you'd use the actual primary key name:
'id_kb' => $this->data['KnowledgeBase']['id_kb']
btw, I'm not sure why you are (re)building the data array, but if it's to make sure that only specific fields are saved, then you could use the fieldList option instead:
$this->data['KnowledgeBase']['kb_last_update'] = date('Y-m-d G:i:s');
$options = array(
'fieldList' => array(
'kb_title',
'kb_content',
'kb_last_update',
'kb_segment'
)
);
$this->KnowledgeBase->save($this->data, $options);

Categories