Saving multiple row with counterCache - mysql

I have problem with counterCache in cakePHP 2.6.4.
I need to save multiple rows to bloggers_products table and i want to increment Bloggers.products_all for each product. For now products_all is allways incremented once.
BloggersProduct belongsTo Blogger
Blogger hasMany BloggersProduct
BloggersProduct Model
'Blogger' => array(
'className' => 'Blogger',
'counterCache' => array(
'products_all' => true,
'reviews' => array('NOT' => array('BloggersProduct.review' => '0000-00-00'))
)
)
I was trying to save data in loop and with saveMany.
$i = 0;
$save = [];
$this->loadModel('BloggersProduct');
foreach ($data as $product) {
// $save = [];
// $save['product_id'] = intval($product);
// $save['blogger_id'] = $blogger_id;
// $save['send_at'] = date('Y-m-d', time());
//
// $this->BloggersProduct->create();
// $this->BloggersProduct->save($save, array('counterCache' => true));
$save[$i]['product_id'] = intval($product);
$save[$i]['blogger_id'] = $blogger_id;
$save[$i]['send_at'] = date('Y-m-d', time());
$i++;
}
debug($save);
$res = $this->BloggersProduct->saveMany($save, array('counterCache' => true));
When i edit or delete any of related products counters set to true value.

Answer was simple:
$this->YourModel->cacheQueries = false;

Related

API Create Multiple Input Laravel

I'm currently creating API for multiple inputs using laravel. The data will be stored into two tables : Order and Detail_Order. One order can have many detail orders.
But now, the data only stored into Order table, and got an error: ErrorException: Invalid argument supplied for foreach() in file. Does anyone know how? Thank you.
Here's my code :
public function createDetail($total_passenger, $id_trip, $id_users, Request $request){
$trip = Trip::where(['id_trip' => $id_trip])->get();
$seat = $request->id_seat;
if(Detail_Order::where(['id_trip' => $id_trip, 'id_seat' => $seat])
->where('status', '!=', 5)
->exists()) {
return $this->error("Seat has been booked");
}else{
$order = new Order();
$order_select = Order::select('id_order');
$order_count = $order_select->count();
if ($order_count === 0) {
$order->id_order = 'P1';
}else{
$lastrow=$order_select->orderBy('created_at','desc')->first();
$lastrow_id = explode('P', $lastrow->id_order);
$new_id = $lastrow_id[1]+1;
$order->id_order = 'P'.$new_id;
}
$order->id_trip = $id_trip;
$order->id_users = $id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = 'O4';
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'gender' => $request->gender[$key],
'departure' => $request->departure[$key],
'destination' => $request->destination[$key],
'phone' => $request->phone[$key],
'status' => 1
]);
}
return response()->json([
'status' => true,
'message' => "Successfully saved data",
'data' => $order
]);
}

conditions doesn't work on hasMany association using contain in cakephp 3

I am trying to search on several conditions on Users Model and Addresses Model. Here Addresses Model are associated with Users Model in hasMany relation. Any condition on Users Model working fine but not working in Addresses Model. Here is my code snippet.
$this->hasMany('Addresses', [
'foreignKey' => 'user_id',
'joinType' => 'LEFT'
]);
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
$options = array();
$status = $this->request->getQuery('status');
$options = array_merge(array('Users.status' => $status), $options);
$profile = array();
$phone = $this->request->getQuery('phone');
$profile = array_merge(array('Addresses.phone' => $phone), $profile);
$addressArr = array('Addresses.user_id', 'Addresses.mobile', 'Addresses.phone', 'Addresses.country_id', 'Addresses.state_id', 'Addresses.city', 'Addresses.zipcode', 'Addresses.address_line1');
$uses = $this->find('all')
->select(['Users.id', 'Users.user_type_id', 'Users.first_name', 'Users.last_name', 'Users.email', 'Users.image', 'Users.status', 'Users.social_type'])
->contain([
'Addresses' => function ($q) use ($addressArr, $profile) {
return $q->select($addressArr)->where($profile);
}
])
->where($options)
->offset($offset)
->limit($limit)
->toArray();
return $uses;

Yii2 display data from phpexcel in view before saving to database

I am still on the process of learning Yii 2 framework. I was able to create a form that uploads excel file then save to database using phpexcel. I want to enhance it in a way that the data from the uploaded excel will be displayed on a table in view so the user can check the data if they are the same with the excel file. After checking, the user will have two options whether CANCEL or CONTINUE.
Here is my controller method to read file and save:
public function importExcel($model, $readFile, $dir)
{
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
// ->setFormatCode( \PHPExcel_Style_NumberFormat::FORMAT_TEXT );
if($row == 9) {
continue;
}
$document = new Document();
$document->type_id = ($rowData[0][0] == 'Ordinance' ? 1 : 2);
$document->no = $rowData[0][1];
$document->series = $rowData[0][2];
$document->title = $rowData[0][3];
$document->author = $rowData[0][5];
$document->date_approved = date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10]));
$document->region_c = $model->region_c;
$document->province_c = $model->province_c;
$document->citymun_c = $model->citymun_c;
$document->catParent = 1;
$document->category_id = 1;
$document->file_url = $dir . '/unzip/' . $rowData[0][13];
$document->save();
}
}
I did this and it worked.
try {
$readFileType = \PHPExcel_IOFactory::identify($readFile);
$objReader = \PHPExcel_IOFactory::createReader($readFileType);
$objPHPExcel = $objReader->load($readFile);
}
catch(Exception $e) {
die('Error reading data from excel file.');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
for($row = 9; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A'. $row . ':' . $highestCol . $row, NULL, TRUE, FALSE);
$objPHPExcel->getActiveSheet()
->getStyle('A'. $row . ':' . $highestCol . $row)
->getNumberFormat()->setFormatCode('0000');
if($row == 9) {
continue;
}
$data[] = array(
'type' => $rowData[0][0],
'no' => $rowData[0][1],
'series' => $rowData[0][2],
'title' => $rowData[0][3],
'author' => $rowData[0][5],
'dateapproved' => date('Y-m-d', strtotime($rowData[0][8].' '.$rowData[0][9].' '.$rowData[0][10])),
'file' => $rowData[0][13]
);
}
$dataProvider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('display', [
'dataProvider' => $dataProvider,
]);
}
If your rowData contain the data and is an array of the row read form excel you can do this
$provider = new ArrayDataProvider([
'allModels' => $rowData,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('your:view', [
'provider' => $provider,
]);
and in your grdiView
<?= GridView::widget([
'dataProvider' => $provider,
......

cakephp2:How to get two different datas with different conditions from the same Model

I'm new to cakephp2 and mysql and need some help.
I want to get the data from yesterday and daybefore yesterday date from the same Model in cakephp2,
However the conditions will be different so I am trying to get the data by making two different methods that contains the find() with different conditions. ,however,I'ts not working. Here is the sample below ↓
This method getYesterday() will return the data as a array but I want to add a condition
that will check if the pageview count is not 0, how will I do that ?
public function getYesterday() {
$yes = array();
$dt = date('Y-m-d', strtotime('-1 day'));
// $dy = date('Y-m-d', strtotime('-2 day'));
$yesterday = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as yesterday_pv'),
'conditions' => array('dt' => "2014/09/26", 'is_crawler' => 0,'count(page_view)>'=>0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($yesterday as $y) {
$yes[] = $y;
//$i++;
}
return $yes;
}
The function below will get the data from daybefore yesterday
public function getDBY() {
$dayyes = array();
$dt = date('Y-m-d', strtotime('-2 day'));
$daybefore = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as daybefore_pv'),
'conditions' => array('dt' => "{$dt}", 'is_crawler' => 0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($daybefore as $dby) {
$dayyes[] = $dby;
//$i++;
}
return $dayyes;
}
The probelem is I'm not sure about this way, Is there a better solution that you can get the different result with different conditions in mysql cakephp2 ? The main thing I want to do Is to get the yesterdays data and daybefore yesterdays data from the same model but I'm not sure how I can do this, I've checked cakes documents but cant find the solution. Sorry for my broken English.

Drupal Tableselects

I can (finally!!!) set a query to return results for a checkbox(es) set within a collapsible fieldset in Drupal 7- however when I try to put it into a tableselect, I get no results. Would someone be able to check out this code and see if you can tell me why? I also have a screen shot of both results- but since I am new here it won't allow me to post it.
$form = array();
$secnum = 1;
$result = db_query('SELECT s.secser_id, s.ser_name FROM {secser} s WHERE s.sec_num = :secnum', array(':secnum' => $secnum));
$options = array();
foreach ($result as $record) {
$options[$record->secser_id] = $record->ser_name;
}
$form['secser']['1'] = array(
'#title' => t('Basic Sanitation'),
'#type' => 'fieldset',
'#collapsible' => TRUE,
);
$form['secser']['1']['secser'] = array(
'#title' => t('Choices'),
'#type' => 'checkboxes',
'#multiple' => TRUE,
'#options' => $options,
'#description' => t('choose!'),
);
$form['secser']['2'] = array(
'#title' => t('Community Systems'),
'#type' => 'fieldset',
'#collapsible' => TRUE,
);
$secnum = 2;
$result = db_query('SELECT s.secser_id, s.ser_name FROM {secser} s WHERE s.sec_num = :secnum', array(':secnum' => $secnum));
$opt2 = array();
foreach ($result as $record) {
$opt2[$record->secser_id] = $record->ser_name;
}
$header = array(
'ser_name' => t('Choose Service(s)'),
);
$form['secser']['2']['secser'] = array(
'#type' => 'tableselect',
'#title' => t('Community Systems'),
'#header' => $header,
'#options' => array($opt2),
'#multiple' => TRUE,
);
I haven't tried running your code, but it looks like your options are an array which contains another array.
#options' => array($opt2),
because $opt2 is an array, this should be:
#options' => $opt2,
the same way you have the options set up in your checkboxes