update multiple array values with multiple ids in laravel 5.1 - arrays

My query as follows
$dueid = array('1','2');
for($n = 0; $n< count($post['percentage']); $n++) {
$due=invoiceduedates::whereIn('id',$dueid)
->update(array(
'percentage' => $post['percentage'][$n],
'amount'=>$post['pamount'][$n],
'date' => $post['date'][$n]
)
);
}
But in table,at 1st and 2nd ids the 2nd array data is getting updated.Please help me to sort it out.

I don't know what you what to get... but in this way it's normal that you get what you get. I can only sugest you to try like this:
$dueid = array('1','2');
$dues = invoiceduedates::whereIn('id',$dueid)->get();
for($n = 0; $n< count($post['percentage']); $n++) {
$due = $dues->find($dueid[$n+1]);
$due->update(array(
'percentage' => $post['percentage'][$n],
'amount'=>$post['pamount'][$n],
'date' => $post['date'][$n]
)
);
}

Related

Cakephp 3.0 REST API add conditions in API response

Can we set conditions in xml response. Like there is status fields in database that is in numeric like 0,1,2,3 and we want to show it like below
0 for => Complete
2 for => Cancelled
2 for => Return
5 for => Refund.
How can we add a new fields in xml response if the fields does not exist in database ?
Lets suppose you are fetching the sales report from Sales table in Cakephp 3.0 Using rest API.
If you want to customize, rename, add few fields in response of Rest API You can do it like below
REST API URL will be something like below
https://example.com/api/index.json?fromdate_utc=2016-10-03&todate_utc=2016-10-03
And functino in controller be something like below:-
public function index($fromdate = null, $todate = null)
{
//set date range for
if(!empty($_GET['fromdate_utc']) && !empty($_GET['todate_utc'])){
// if from amd to date are same add +1 day in to date to get result
$to_date = date('Y-m-d', strtotime($_GET['todate_utc'] . ' +1 day'));
$dateRage = array('Sales.SalesDate >= ' => $_GET['fromdate_utc'], 'Sales.SalesDate <=' => $to_date);
}else{
$dateRage = array();
}
$conditions = array(
'and' => array($dateRage),
);
//$this->Auth->allow();
$sales = $this->Sales->find('all', array(
'conditions' => $conditions
))
->select(['SalesNo', 'SalesDate', 'TotalValue', 'TotalDiscount', 'NetTotal', 'PaymentMode', 'Status'])
->where(['StoreId' => '8','Status !=' => '2','Status !=' => '4'])->andWhere(['Status !=' => 1])->andWhere(['Status !=' => 4]);
//->limit(3);
$salesResponse = array();
//echo '<br/>Count no of output => '.$sales->count();
if($sales->count() >0 ){
foreach($sales as $key=>$salesData){
//re generate the array as per your requirements
$salesResponse[$key]['SalesNo'] = $salesData->SalesNo;
$salesResponse[$key]['SalesDate'] = $salesData->SalesDate;
$salesResponse[$key]['TotalValue'] = $salesData->TotalValue;
$salesResponse[$key]['TotalDiscount'] = $salesData->TotalDiscount;
$salesResponse[$key]['NetTotal'] = $salesData->NetTotal;
$salesResponse[$key]['SaleTax'] = 0; // add new fields that does not exist in database
$salesResponse[$key]['PaymentMode'] = $salesData->PaymentMode;
// change the status from numeric to character and pass it to response
if($salesData->Status == 5){
$salesResponse[$key]['Status'] = 'Refund';
}elseif($salesData->Status == 3){
$salesResponse[$key]['Status'] = 'Return';
}elseif($salesData->Status == 2){
$salesResponse[$key]['Status'] = 'Cancelled';
}elseif($salesData->Status == 0){
$salesResponse[$key]['Status'] = 'Complete';
}
}
}else{
$salesResponse = array('Error ! sorry not found any record.');
}
$this->set([
'sales' => $salesResponse,
'_serialize' => ['sales']
]);
}
If you're okay with having a slightly different name for the status in the XML, you could create a virtual field called, for example, status_text. Add a protected function _getStatusText in your Sale entity class which returns the desired text based on the status integer, and also add protected $_virtual = ['status_text']; to the Sale class, and you should start getting the status text in your XML.

cakephp looping only save first row of data, others row not saving

Looping to save each column field picture1pic6:
Please help, i using cake php version 2.0, try to do looping to save each column, but only the first row data save, the data should be save like attached picture1.Hope someone can help, i tried to figure out 2 weeks. V_COUNT i hardcode the number to 23.
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
$this->IPI->setSource($table_name);
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$this->request->data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$this->request->data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$this->request->data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$this->request->data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->create();
$this->IPI->save($this->request->data);
}
}
try this
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
$data = array();
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->setSource($table_name);
$this->IPI->create();
$this->IPI->save($data);
}
}

Why multiple records is not updating using cakephp?

I am giving my controller code below :
for ($i = 0; $i < count($club_open); $i++) {
$infomation["ClubOpenDay"]["club_id"] = $club_id;
$infomation["ClubOpenDay"]["days"] = $club_open[$alpha[$i]];
$infomation["ClubOpenDay"]["open_time"] = $club_open_time[$alpha[$i]];
$infomation["ClubOpenDay"]["close_time"] = $club_close_time[$alpha[$i]];
$infomation["ClubOpenDay"]["status"] = $club_status[$alpha[$i]];
$this->ClubOpenDay->updateAll(
array('ClubOpenDay.status' => "'".$infomation["ClubOpenDay"]["status"]."'"),
array('ClubOpenDay.club_id' => "'".$club_id."'")
);
}
using this code, I am not able to update multiple records. Any idea?
instead of this:
$this->ClubOpenDay->updateAll(
array('ClubOpenDay.status' => "'".$infomation["ClubOpenDay"]["status"]."'"),
array('ClubOpenDay.club_id' => "'".$club_id."'")
);
write the following:
$this->ClubOpenDay->updateAll(
array('ClubOpenDay.status' => $infomation["ClubOpenDay"]["status"]),
array('ClubOpenDay.club_id' => $club_id)
);

issues with saveAssociated cakephp

I'm having some issues trying to save an article that has 4 pictures. The thing is that i need to use the article id in order to name the pictures like article_id."-"$i
Since I have only 4 pictures per article this $i should be from 1 to 4 or from 0 to three.
Now the problem is that in order to achieve this i need to create and save Article model so i can have an id to use, but then after performing all the scripting to make the thumbs and form the names, when I go Article->saveAssociated() i have two times the article record created!! i tried to set the id to "-1" before saving but nothing...
Any suggestion will be very much appreciated !!!
Code:
public function add() {
if ($this->request->is ( 'ajax' )) {
$this->layout = 'ajax';
} else {
$this->layout = 'default';
}
if ($this->request->is ( 'post' )) {
$this->Article->create ();
$this->request->data ['Article'] ['time_stamp'] = date ( 'Y-m-d H:i:s', time () );
if ($this->Article->save($this->request->data) ) {
for ($i=0; $i<4; $i++){
$img_path = "./images/";
$extension[$i] = end(explode('.', $this->request->data['Image'][$i]['image']['name']));
$this->request->data['Image'][$i]['image'] = array('name'=>$this->Article->id."-".$i, 'tmp_name' => $this->request->data['Image'][$i]['image']['tmp_name']);
// $this->request->data['Image'][$i]['name'] = $this->Article->id."-".$i;
$this->request->data['Image'][$i]['ext']= $extension[$i];
$target_path[$i] = $img_path . basename($this->request->data['Image'][$i]['image']['name'].".".$extension[$i]);
if(!move_uploaded_file($this->request->data['Image'][$i]['image']['tmp_name'], $target_path[$i])) {
die(__ ( 'Fatal error, we are all going to die.' ));
}else{
$this->Resize->img($target_path[$i]);
$this->Resize->setNewImage($img_path.basename($this->request->data['Image'][$i]['image']['name']."t.".$extension[$i]));
$this->Resize->setProportionalFlag('H');
$this->Resize->setProportional(1);
$this->Resize->setNewSize(90, 90);
$this->Resize->make();
}
}
$this->Article->id;
pr($this->Article->id);
$this->Article->saveAssociated($this->request->data, array('deep' => true));
//$this->redirect ( array ('action' => 'view', $this->Article->id ) );
pr($this->Article->id);
exit;
$this->Session->setFlash ( __ ( 'Article "' . $this->request->data ["Article"] ["name"] . '" has been saved' ) );
} else {
$this->Session->setFlash ( __ ( 'The article could not be saved. Please, try again.' ) );
}
}
$items = $this->Article->Item->find ( 'list' );
$payments = $this->Article->Payment->find ( 'list' );
$shippings = $this->Article->Shipping->find ( 'list' );
$this->set ( compact ( 'items', 'payments', 'shippings' ) );
}
Instead of
$this->Article->saveAssociated();
which would save the Article AGAIN, just save the images separately using something like this:
foreach($this->request->data['Image'] as &$image) {
$image['name'] = 'whatever_you_want' . $this->Article->id;
$image['article_id'] = $this->Article->id;
}
$this->Article->Image->save($this->request->data['Image']);
Another option (not necessarily better - just another option) would just be to append the newly-created Article's id to the existing Article array, then saveAssociated(). If the Article has an id in it's data, it will update instead of create. I would suggest the first answer above, but - just brainstorming other options in case this helps for someone's scenario:
// 1) save the Article and get it's id
// 2) append the `id` into the Article array
// 3) do your image-name manipulation using the id
// 4) saveAssociated(), which updates the Article and creates the Images

Using read() in cakephp to retrieve row with array of data

I want to know if it is possible to retrieve a row from the database using something similar to the following:
if (!empty($this->params['form'])) {
$place = array();
$place['city'] = $this->params['form']['city'];
$place['area'] = $this->params['form']['state'];
$place['country'] = $this->params['form']['country'];
$place['iso'] = $this->params['form']['iso'];
$this->Place->set($place);
$place_found = $this->Place->read();
}
Is there some way I can preset the data in the Place model using the array and then use Place read. I'm looking for something simple like the usual:
$this->Place->id = 7;
$place_found = $this->Place->Read();
I have also tried doing this:
$this->Place->city = blah;
$this->Place->area = foo; etc....
$place_found = $this->Place->read();
However, that also does not work.
Haven't you ever used find()?! read() only fetches a row with the ID passed.
$place_found = $this->Place->find('first', array(
'conditions' => array(
'Place.city' => $city,
'Place.area' => $area
// etc
)
));
If you need to build the conditions manually you can create a conditions array to pass like so:
$placeConditions = array();
$placeConditions['city'] = $city;
if($area) {
$placeConditions['area'] = $area;
}
$places = $this->Place->find('first', array('conditions' => $placeConditions));
I suggest you read the page I linked, you will soon find out there is never a reason to use the read() method.
In model you could do:
$this->id = 3; //place id
$this->Place->read();
Hope it helps
I think this approach is what you're looking for(with your code):
if (!empty($this->params['form'])) {
$place = array();
$place['city'] = $this->params['form']['city'];
$place['area'] = $this->params['form']['state'];
$place['country'] = $this->params['form']['country'];
$place['iso'] = $this->params['form']['iso'];
//$this->Place->set($place); //don't need it here I think
$place_found = $this->Place->find('all',array('conditions'=>$place));
}
You'll have to use "find()", not "read()", but - it's almost as simple as your example code and should work. (also, there's a shortcut for the array_push() I believe, but - I like to use this for readability - personal preference):
if (!empty($this->params['form'])) {
$conditions = array();
array_push($conditions, array('Place.city' => $this->params['form']['city']);
array_push($conditions, array('Place.state' => $this->params['form']['state']);
array_push($conditions, array('Place.country' => $this->params['form']['country']);
array_push($conditions, array('Place.iso' => $this->params['form']['iso']);
$this->Place->set($place);
$place_found = $this->Place->find('all', array('conditions'=>$conditions));
}

Resources