Laravel/Mysql: unable to set field to null - php

I am working on a laravel project and trying to duplicate a record in mysql db.
after replication I want to set a field value to null(appointment_status).
everything is working except the new record's value (appointment_status) is the same as the original record even tho I set it to null.
$newAppointment = $appointment->replicate();
//push to get the id for the cloned record
$newAppointment->push();
$newAppointment->duplicated_from_id = $appointment->id;
$newAppointment->appointment_status = null;
$newAppointment->save();
//updating the old appointment
$appointment->duplicated_to_id = $newAppointment->id;
$appointment->save();

Instead of whole code-block, try something like this:
// replicate as the new record with some different fields
$newAppointment = $appointment->replicate()->fill([
'duplicated_from_id' => $appointment->id,
'appointment_status' => null,
])->save();
// update some fields of initial original record
$appointment->update([
'duplicated_to_id' => $newAppointment->id,
]);
For more check out this.

Related

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

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.

I am trying to update but it is adding a new row

this is my code for updating:
PS: empid is a foreign key but i think that shouldnt be the reason and the code is in CakePHP
if($this->request->is('post'))
{
$this->request->data["Leave"]["empid"] = $this->request->data["id"];
$this->Leave->empid = $this->request->data["Leave"]["empid"];
$this->request->data["Leave"]["leave_start"] = $this->request->data["start_date"];
$this->request->data["Leave"]["leave_end"] = $this->request->data["end_date"];
$this->request->data["Leave"]["leave_taken"] = $this->request->data["leave_taken"];
if($this->Leave->save($this->request->data['Leave']))
{
return $this->redirect(array('action' => 'manage_leave'));
}
}
// This code is inserting a new row instead of updating and also not adding any value in the new row
May be your trying to update the foreign table data using simple save.
Update multiple records for foreign key
Model::updateAll(array $fields, mixed $conditions)
Example
$this->Ticket->updateAll(
array('Ticket.status' => "'closed'"),
array('Ticket.customer_id' => 453)
);
Simple save for the primary key
Make sure that your HTML has empid
echo $this->Form->input('Leave.empid', array('type' => 'hidden'));
Save Model
$this->Leave->empid = $this->request->data["Leave"]["empid"]; //2
$this->Leave->save($this->request->data);
In between, you can also try to set the model data and check the $this->Leave->validates() and $this->Leave->validationError if they are giving any validation errors.
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);
// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
You can find more information about all Saving your data
Hope this helps you :)
And in case if $empid is primary key of corresponding table of Leave model (e.g leaves), Just replace:
$this->Leave->empid = $this->request->data["Leave"]["empid"];
By
$this->Leave->id = $this->request->data["Leave"]["empid"];

Laravel 5 eloquent model won't let me update

I do have the invitations table set up and in the database. I use it for other purpose such as adding more...
my goal: update the first record with a new value to a field:
I tried:
$invitation = new MemberInvitation();
$invitation1 = $invitation->find(1);
$invitation1->status = 'clicked';
$invitation1->save();
And also:
$invitation1 = \App\Model\MemberInvitation::find(1);
$invitation1->status = 'clicked';
$invitation1->save();
both ended with:
Creating default object from empty value
EDIT:
This piece of code worked and updated my records correctly -- I just can't do it via Eloquent's model:
\DB::table('member_invitations')->where('id', '=', $member_invitation->id)
->update(array('status' => 'clicked', 'member_id' => $member->id));
what am I missing?
Try this.
$invitation = MemberInvitation::findOrFail(1);
$invitation->status = 'clicked';
$invitation->save();
If that doesnt work, please show your model
find(1) doesn't mean "give me the first record", it means "give me the first record where id = 1". If you don't have a record with an id of 1, find(1) is going to return null. When you try and set an attribute on null, you get a PHP warning message "Creating default object from empty value".
If you really just want to get the first record, you would use the first() method:
$invitation = \App\Model\MemberInvitation::first();
If you need to get a record with a specific id, you can use the find() method. For example, to translate your working DB code into Eloquent, it would look like:
$invitation = \App\Model\MemberInvitation::find($member_invitation->id);
$invitation->status = 'clicked';
$invitation->member_id = $member->id;
$invitation->save();
The answer is obvious based on your reply from May 15th.
Your "fillable" attribute in the model is empty. Make sure you put "status" in that array. Attributes that are not in this array cannot up modified.

PostgreSQL Update Issue With Quotation('')

I'm using PostgreSQL & Codeigniter. There is a table called folio in the database. It has few columns containing remarks1, remarks2, remarks3 as well. Data for the all the other columns are inserted when the INSERT statement executes for the 1st time.
When I try to execute below UPDATE statement later for the below 3 columns, remarks1 column get updated correctly. But remarks2, remarks3 columns are updated with ''.
UPDATE "folio" SET "remarks1" = 'test remark', "remarks2" = '', "remarks3" = '' WHERE "id" = '51';
Given that remarks1, remarks2, remarks3 columns data type is character varying. I'm using Codeigniter active records. At a time all 3 columns could be updated else single column could be updated depending on the user input.
What could be the issue? How can I fix this? Why columns are updated with ''?
As requested the php array in CI would be below
$data = array(
'remark1' => $this->input->post('remark1'),
'remark2' => $this->input->post('remark1'),
'remark3' => $this->input->post('remark1')
);
Function which saves the data contains below two lines only
$this->db->where('id', $folio_id);
$this->db->update('folio', $data);
Those columns are updated with '' because you tell them to?
Let's take a closer look at the query
UPDATE "folio"
SET
"remarks1" = 'test remark',
"remarks2" = '',
"remarks3" = ''
WHERE
"id" = '51';
First you select the table folio for the update.
Then you tell it to update remarks1 through remarks3 with new values. For remarks2 and remarks3 you specify to set them to an empty string. And that's what's going to happen.
Last but not least, you tell it to only apply this update to rows where id equals 51.
So, in order to only update remarks1 you can simply remove the other columns from your update:
UPDATE "folio"
SET
"remarks1" = 'test remark'
WHERE
"id" = '51';
Update:
I'm by far not a CI expert, but from what I see, I'd change the $data array to only contain information for remark1:
$data = array(
'remark1' => $this->input->post('remark1')
);
And (from my understanding) it should only update this single column.

How to update record array using cakephp and mongodb

I have a problem. I have this structure of db in mongodb:
id:"xxx",
is_validated: "xxx",
validation_code:"xxx",
profile:[
{
profile_pic:"xxx",
firstname:"xxx",
lastname:"xxx",
}
]
I am using cakephp. When I update the record, I use this:
$this->User->set('id', "xxx");
$this->User->set('profile', array('firstname' => 'Benedict'));
$this->User->save()
When I save the record, the whole array of profile is deleted and only saves the "firstname":
id:"xxx",
is_validated: "xxx",
validation_code:"xxx",
profile:[
{
firstname:"xxx"
}
]
I need to be able to save the firstname without deleting the other array records of mongodb using cakephp
Do you not follow the standard convention when using MongoDB? (documentation):
// where '1' is the id of your user
$this->User->read(null, 1);
// set the new value for the field
$this->User->set('profile', array('firstname' => 'Benedict'));
// commit the changes to the database
$this->User->save();
Update
If the above doesn't work, try reading the whole record and modifying accordingly:
// set the active record
$this->User->id = 1;
// read the entire record
$user = $this->User->read();
// modify the field
$user['User']['profile']['firstname'] = 'Benedict';
// save the record
$this->User->save($user);
The reason this is happening is because you are asking for the profile field to be updated with the array that you pass. This then duly replaces the current profile array with yours.
To get round this you will have to pass the complete array in i.e. with the keys you want to keep and their values as well as the keys you want to change.

Categories