I've save function in php
$post = $this->request->post('event');
$events = ORM::factory('Tasks_Manage')->values();
try {
$return = array();
foreach ($events as $event) {
$title = $event['name']['taskName'];
$time = $event['time'];
$return[] = $event;
$event->save();
}
return array(
'return' => $return;
Data, are existing in headers but array in response is empty. Please help
$conn->insert('user', array('username' => 'jwage'));
// INSERT INTO user (username) VALUES (?) (jwage)
Im was rebuild my code
$events = $this->request->post('event');
$h = ORM::factory('Tasks_Manage');
$return = array();
foreach($events as $event) {
$title = $event['name']['taskName'];
$time = $event['time'];
$return[] = $event;
$h->values( array(
'event_id' => $title,
'time' => $time,
))->save();
}
return array(
'event' => $events);
Now i can save value in database, but only one record. Why i cant save few records simultaneously? In console response and preview send correct
You don't get all entries of database. Use find_all() method (using values() method is wrong)
$events = ORM::factory('Tasks_Manage')->find_all();
Related
I wrote an api call in my Symfony project that returns all fields from my entity with the query defined below..
Now, I need to define just three fields like 'id', 'name', 'value' and to pull values from that fields that are currently stored in a database.
public function getChartData() {
$myResults = $this->getMyRepository()
->createQueryBuilder('s')
->groupBy('s.totalCollected')
->orderBy('s.id', 'ASC')
->getQuery()
->getArrayResult();
$result = array("data" => array());
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
}
The problem is it return just totalCollected field.
One of errors are Call to a member function getId() on array and so on, and I can't figure out a way to pull data from db...
I cannot see in your code where $schoolResult come from but lets guess it string key of some sort.
Notice you trying to set 3 value on the same key so only the last one remains.
Look at:
$a = array();
$a["key"] = 4;
$a["key"] = 6;
It is simple to see that $a["key"] will contains 6 and not 4 or both.
When you do:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
You override the data in $result['data'][$schoolResult] therefor only try totalCollected is there as the last one to set.
In order to fix that you can use:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult]["id] = $label["id"];
$result['data'][$schoolResult]["name"] = $label["name"];
$result['data'][$schoolResult]["totalCollected"] = $label["totalCollected"];
}
Hope that helps!
I am trying to insert/update +/- 10k rows with a foreach loop. The complete loop duration is about 3-5minutes. Are there any tips on my code to do the insertion of update faster? The $rows are retrieved from a xls file converted to domdocument.
foreach($rows as $key => $row)
{
if($key < 1){continue;}
$cells = $row -> getElementsByTagName('td');
foreach ($cells as $cell) {
$project_id = $cells[0]->nodeValue;
$title = $cells[1]->nodeValue;
$status = $cells[2]->nodeValue;
$projectmanager = $cells[3]->nodeValue;
$engineer = $cells[4]->nodeValue;
$coordinator = $cells[5]->nodeValue;
$contractor_a = $cells[6]->nodeValue;
$contractor_b = $cells[7]->nodeValue;
$gsu = $cells[9]->nodeValue;
$geu = $cells[10]->nodeValue;
$query = $this->Projects->find('all')->select(['project_id'])->where(['project_id' => $project_id]);
if ($query->isEmpty()) {
$project = $this->Projects->newEntity();
$project->title = $title;
$project->project_id = $project_id;
$project->status = $status;
$project->projectmanager = $projectmanager;
$project->engineer = $engineer;
$project->coordinator = $coordinator;
$project->contractor_a = $contractor_b;
$project->contractor_b = $contractor_a;
$project->gsu = date("Y-m-d H:i:s");
$project->geu = date("Y-m-d H:i:s");
$project->gsm = date("Y-m-d H:i:s");
$project->gem = date("Y-m-d H:i:s");
if ($this->Projects->save($project)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}else{
debug($project->errors());
}
}else{
continue;
$query->title = $title;
$query->status = $status;
$query->projectmanager = $projectmanager;
$query->engineer = $engineer;
$query->coordinator = $coordinator;
$query->contractor_a = $contractor_b;
$query->contractor_b = $contractor_a;
$query->gsu = $gsu;
$query->geu = $geu;
if ($this->Projects->save($query)) {
//$this->Flash->success(__('The project has been saved.'));
continue;
}
}
}
//$this->Flash->error(__('The project could not be saved. Please, try again.'));
}
For faster bulk inserts don't use entities but rather generate insert queries directly.
https://book.cakephp.org/3.0/en/orm/query-builder.html#inserting-data
Ello, my vriend.
The TableClass->save() method is useful when saving one single record, in your case, you should use TableClass->saveMany() instead.
For this to happen, you need to treat your entities as arrays inside your foreach.
After the foreach, you will use another method from the tableclass (newEntities) to convert the array into entities before finally save them.
Basic example:
//Lets supose our array after our foreach become something like this:
$all_records =
[
//Each item will be an array, not entities yet
[
'name' => 'I.N.R.I.',
'year' => '1987',
'label' => 'Cogumelo',
'country' => 'Brazil',
'band' => 'Sarcófago',
'line_up' => '[{"name":"Wagner Antichrist","role":"Vomits, Insults"},{"name":"Gerald Incubus","role":"Damned Bass"},{"name":"Z\u00e9der Butcher","role":"Rotten Guitars"},{"name":"D.D. Crazy","role":"Drums Trasher"}]'
],
//Another record coming in..
[
'name' => 'Eternal Devastation',
'year' => '1986',
'label' => 'Steamhammer',
'country' => 'Germany',
'band' => 'Destruction',
'line_up' => '[{"name":"Marcel Schmier","role":"Vocals, Bass"},{"name":"Mike Sifringer","role":"Guitars"},{"name":"Tommy Sandmann","role":"Drums"}]'
]
];
//Time to get the tableclass...
$albums = TableRegistry::get('Albums');
//Time to transform our array into Album Entities
$entities = $albums->newEntities($all_records);
//Now, we have transformed our array into entities on $entities, this is the variable we need to save
if(!$albums->saveMany($entities))
{
echo "FellsBadMan";
}
else
{
echo "FellsGoodMan";
}
You can read more about here
I have a controller that I would like to return a JSON response that has multiple arrays. First, I'll present my controller:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}
This is an example, but at this time if I just dd($billToEmail), I will get multiple rows returned of all of the data that I requested (all of which are emails), but when I return the JSON specific return "billersEmails", I only get one of those emails returned.
I know there must be a possibility of the multiple emails being returned, but I haven't found an appropriate response anywhere as of yet.
You have to use array as you have multiple records otherwise it will over-write existing values. change your code as below:
<?php
public function notificationEmails(Request $request)
{
$shipment = Shipment::findOrFail($request->shipmentID);
$billToAccount = $shipment->billtoAccount;
$billToAccountUsers = $billToAccount->users;
$billToEmail = array();
$shipToEmail = array();
$shipFromEmail = array();
foreach ($billToAccountUsers as $billToAccountUser){
$billToEmail[] = $billToAccountUser->email;
}
$shipToAccount = $shipment->shiptoAccount;
$shipToAccountUsers = $shipToAccount->users;
foreach ($shipToAccountUsers as $shipToAccountUser){
$shipToEmail[] = $shipToAccountUser->email;
}
$shipFromAccount = $shipment->shipfromAccount;
$shipFromAccountUsers = $shipFromAccount->users;
foreach ($shipFromAccountUsers as $shipFromAccountUser){
$shipFromEmail[] = $shipFromAccountUser->email;
}
return response()->json([
'details' => $shipment,
'billersEmails' => $billToEmail
]);
}
I've a table in which I have to save multiple data, in my controller I've implemented this action:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
$model = new SlidersImages();
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
if ($model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()) {
$s['image_'.$key] = $model;
$model->display_order = $value;
//$result = ($t = $model->update()) ? $result + $t : $result;
$result = $model->save() && $result;
}
}
}
return $result;
}
The data received are right but not the result, the only thing that the action do is to add new table row with slider_id and image_id equal to NULL, why the model doesn't save correctly?
Thanks
The thing is when you call
$model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
you don't change the $model object itself. Essentially you are calling:
SlidersImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
So, later when you call $model->save() you are saving a $model object with empty attributes (you only changed display_order)
My advise here: try to assign the result of the ->all() call to the new var and then work with it:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
$models = SliderImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all();
if (count($models)) {
// loop through $models and update them
}
}
}
return $result;
I have a function as follow:
function get_employee_information()
{
$this->db
->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
}
I'm trying to access this data from within an output to template, like this:
$this->get_employee_information();
$output = $this->template->write_view('main', 'records', array(
'employee_names' => $employee_names,
'employee_ids' => $employee_ids,
), false);
Yet this isn't displaying anything. I feel like this is something small and I should know better. When I tun print_r($arrayname) on either array WITHIN the function, I get the suspected array values. When I print_r OUTSIDE of the function, it returns nothing.
Your function is not returning anything. Add the return shown below.
function get_employee_information()
{
$this->db->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
return array(
'employee_names'=>$employee_names,
'employee_ids'=>$employee_ids,
);
}
You are not setting the return value of the function to a variable
$employee_info = $this->get_employee_information();
$output =
$this->template->write_view(
'main', 'records',
array(
'employee_names' => $employee_info['employee_names'],
'employee_ids' => $employee_info['employee_ids'],
),
false
);