How to clone/copy a sql record with CakePhp?
Is there a native way or do I need to find my record and then save it?
You need to use the find and save function.
$record = $this->Model->findById(1);
$record['Model']['id'] = NULL;
$this->Model->save($record);
There is no native "copy" command by itself. But a find/read operation followed by a create/save should work.
$row = $this->Model->findById(1);
$this->Model->create(); // Create a new record
$this->Model->save($row); // And save it
Would copy the row with id 1.
Related
I have a problem with my Laravel crud application for Registrations.
There are these tables: Registration, ExtraRegistration (with a registration_id, extra_id and extraoptions_id),
Extra and ExtraOptions (with the Extra_id).
In the RegistrationController when i add a Registration it makes a new record in the ExtraRegistration with the extraoptions_id and the extra_id. the extra_id is the name of the option and the extraoptions_id is the id of the option you selected.
But now, when you click on edit a record, it shows all the information. the problem is that when you change the extraoption, it makes another record, and not change the select.
And when you have edited something and you look at it again, it still shows the option before you edited it.
RegistrationController
$options = Extra::where("exa_form_id", $distance->asd_form_id)->get();
foreach($options as $option){
$input_name = "option_" . $option->exa_id;
$input_option = $request->$input_name;
if(!is_null($input_option)){
$input_name_extra = "extraoptions_" . $option->exa_id;
$input_option_extra = $request->$input_name_extra;
$registrationextra = new ExtraRegistration();
$registrationextra->iea_registration_id = $registration->isg_id;
$registrationextra->iea_extra_id = $input_option;
$registrationextra->iea_extraoption_id = $input_option_extra;
$registrationextra->iea_price = $option->exa_price;
$registrationextra->save();
}
}
$registration->isg_options = $input_option;
$registration->isg_option_extra_id = $input_option_extra;
Edit:
I want a check before it makes a new ExtraRegistration. that if the price that is in the registration already exists in that registration_id(in ExtraRegistration) it doesnt make another record in the ExtraRegistration.
I want to use an if to fix the problem, but not sure where to begin..
Thanks in advance!
It will probably be easier for you if you just use firstOrCreate method that Laravel provides out of the box.
You can check it here:
https://laravel.com/docs/5.8/eloquent#other-creation-methods
That way, you will be able to retrieve the record that you are looking for, if there is any and then perform all the changes on it. If that record doesn't exist, Laravel will create the new record for you which you'll be able to update.
I hope this helps!
You are creating new object of ExtraRegistration() so its inserting/creating new record every time.
Just changes this line
$registrationextra = ExtraRegistration::find($id);//any id to fetch record
I need to read all records from table agreements, make changes in filed payments, and update all records, save to table. So, my problem is, that save() only create empty record. Do not update exists record. I show you how:
Reading from table:
$agreements = $this->Agreement->find('all');
$payments = $this->Payment->find('all');
Manipulation on fields (part of)(example):
$id=0;
foreach ($agreements as $agreement):
for ($i=$first_agreement; $i<=$last_agreement; $i++){
if ( $agreement['Agreement']['agreement_number']==$i){
$agreements[$id]['Agreement']['payment']=$payd[$i];
}
}
$id++;
endforeach;
Writting to table:
$this->Agreement->save();
A echo debug($agreements) shows correct array, i have tryed also :
$this->Agreement->save($agreements);
or
$this->Agreement->save($this->request->data);
Can you help/explain me how to write all record?
Cake 2.5.2 PHP : 5.4.4-14
Model::save() only saves a single record. If you want to save multiple records you need to use Model::saveAll() or Model::saveMany().
I'm trying to use the Joomla framework to make a create in the main content table.[http://docs.joomla.org/How_to_use_the_JTable_class] This works fine except that some data comes from posted variables and some from logic that happens when a file is uploaded moments before (store the random image name of a jpg)
$data=&JRequest::get('post');
this takes a ref to the posted values and I want to add to this Array or Object my field. The code I have makes the new record but the column images, doesnt get my string inserted.
I am trying to do something like$data=&JRequest::get('post');
$newdata=(array)$data;
array_push($newdata,"images"=>"Dog");
i make newdata as data is a ref to the posted variables and i suspect wont there fore allow me to add values to $data.
I'm a flash guy normally not a php and my knowledge is letting me down here.
Thanks for any help
Right, first thing:
$data=&JRequest::get('post');
$data is an array, you do not have to cast it. To add another element to the array as described in the comments do this:
$data['images'] = 'cats';
If you are using normal SQL to do the insert then you would do something like this to get the last inserted id e.g. the id of the row you just inserted:
$db = $this->getDBO();
$query = 'Some sql';
$db->setQuery($query);
if (!$db->query()) {
JError::raiseWarning(100, 'Insert failed - '.$db->getErrorMsg());
}
$id = $db->insertid();
If you are developing in Joomla I suggest you use the db functions provided to you rather than mysql_insert_id();
[EDIT]
If you want to use store then you can get the last inserted id like so:
$row->bind($data);
$row->check();
$row->store();
$lastId = $row->id;
I'm writing a small application that will write the contents of a csv file to a database in CodeIgniter, but I'm having difficulty checking for dupes before write. Since this is a fairly common task, I was wondering how some of the professionals (you) do it. For context and comparison, here is my (currently non-working) code:
$sql = "SELECT * FROM salesperson WHERE salesperson_name='" . $csvarray['salesperson_name'][$i] . "'";
$already_exists = $this->db->query($sql);
if (sizeof($already_exists) > 0) {
//add to database
}
Any input at all short of "You suck!" (I already hear that from my own brain twice an hour at this point) will be greatly appreciated. Thanks.
What you're doing will work, but as above the comparison should be "== 0" not "> 0".
You can also use CodeIgniters built in num_rows method instead of using sizeof, like so:
$sql = "your query";
$query = $this->db->query($sql);
if ($query->num_rows() == 0) {
// no duplicates found, add new record
}
As a side note, if you're using CodeIgniter then it's worthwhile to use Active Record to build your queries instead of writing SQL. You can learn more about it here: CodeIgniter - Active Record
Firstly you probably want (rather than >0)
if (sizeof($already_exists) == 0) {
//add to database
}
Also could just push all your data to a temporary staging table, which you could then clean out with some spiffy sql- and then push back to your staging table.
Taking a punt on you using mysql (either that or postgres if you are phping) You could try this (taken from http://www.cyberciti.biz/faq/howto-removing-eliminating-duplicates-from-a-mysql-table/)
You will have to change your .ID to your primary key
delete from salesperson_temptable
USING salesperson_temptable, salesperson_temptable as vtable
WHERE (NOT salesperson_temptable.ID=vtable.ID)
AND (salesperson_temptable.salesperson_name=vtable.salesperson_name)
then when you review the contents of salesperson_temptable you can then insert it back to the salesperson table
I'm using RedBean PHP to dump some data from a web scrape into a database, and I need to retain the legacy IDs, preferably as the primary key field. Is it possible to do this with RedBean?
When I try to set the id as so:
$bean->id = 56;
The row doesn't get inserted - the query that ends up being created instead becomes an "UPDATE WHERE id=56", which does nothing since the record doesn't exist yet.
I solved this by inserting a placeholder with an SQL exec first:
$id = 60000;
$name = 'bob';
R::exec('insert into person(id) values('.$id.')');
$person = R::dispense('person');
$person->id = $id;
$person->name = $name;
R::store($person);
Forcing a specific value on an auto-increment primary index is just asking for race-condition problems. I'd suggest you create a new column legacy_id instead where you save the alternative id.
I have started an redbean github project for this, first version supports to have custom id fields.
You have to tell redbean what the name of the id field is (if not "id")
R::getRedBean()->idFieldMap= array('adres'=>'id_adres','contact'=>'contact_id'); // settings for current database
Future improvements: support custom Foreign keys.
https://github.com/freelanceniek/redbeanx