The code works fine like this. no problem with toArray
$restaurants = Restorant::where(['active'=>1])->orderBy('id', 'desc')->limit(10)->get();
$data = [];
$item = [];
foreach ($restaurants as $rest_key => $rest_value) {
$item = $rest_value->toArray();
$item["ratings"] = [];
$item["time_to_prepare_order_in_minutes"] = [];
$ratings = DB::table('ratings')->where('rateable_id', '=', $rest_value->id)->get();
foreach ($ratings as $rating_key => $ratings_value) {
$item["ratings"][] = [
"sub_id" => $ratings_value->id,
"rating" => $ratings_value->rating,
];
}
$configs = DB::table('configs')->where('key','=','time_to_prepare_order_in_minutes')->where('model_id','=',$rest_value->id)->first();
$item["time_to_prepare_order_in_minutes"] = $configs->value;
$data[] = $item;
}
return response()->json([
'data' => $data,
'status' => true
]);
But I don't know how to do this when I use join. I also did this logic. How can I do this better? My aim is to tire the server as little as possible while retrieving data in json format. I tried to do it with DB->with option but it gave different errors.
$restaurants = DB::table('companies')->select('companies.*', 'configs.key', 'configs.value')->leftJoin('configs', 'configs.model_id', '=', 'companies.id')->where('configs.key', '=', 'time_to_prepare_order_in_minutes')->where('companies.active', '=', 1)->orderBy('companies.id', 'desc')->limit(10)->get();
$columns = Schema::getColumnListing('companies');
$data = [];
$item = [];
foreach ($restaurants as $rest_key => $rest_value) {
foreach ($columns as $col_key => $col_value) {
$cKey = $columns[$col_key];
$item[$cKey] = $rest_value->$cKey;
}
$item["ratings"] = [];
$ratings = DB::table('ratings')->where('rateable_id', '=', $rest_value->id)->get();
foreach ($ratings as $rating_key => $ratings_value) {
$item["ratings"][] = [
"sub_id" => $ratings_value->id,
"rating" => $ratings_value->rating,
];
}
$data[] = $item;
}
return response()->json([
'data' => $data,
'status' => true
]);
I found the source of the problem. The -> sign solved my problem.
$data = [];
$item = [];
foreach ($cityRestaurants as $city_key => $city_value) {
$item = $city_value;
$item->ratings = [];
$ratings = DB::table('ratings')->where('rateable_id', '=', $city_value->id)->get();
foreach ($ratings as $rating_key => $ratings_value) {
$item->ratings[] = [
"sub_id" => $ratings_value->id,
"rating" => $ratings_value->rating,
];
}
$configs = DB::table('configs')->where('key','=','time_to_prepare_order_in_minutes')->where('model_id','=',$city_value->id)->first();
$item->time_to_prepare_order_in_minutes = $configs->value;
$data[] = $item;
}
Related
I have created a custom restful API endpoint in WordPress which returns the JSON with the only required fields.
So with this one when I go to the example.com/wp-json/wl/posts, it returns 5 posts as I have limited the number of the posts.
function wl_posts() {
$args = [
'numberposts' => 99999,
'post_type' => 'post'
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$i++;
}
return $data;
}
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'posts', [
'methods' => 'GET',
'callback' => 'wl_posts',
]);
});
But I also want to add the pagination, so if I add ?page=2 , it should return another 5 posts.
How can that be archived?
When visiting /?rest_route=/ or /wp-json/wp/v2/pages you can drill down into ie. wp/v2/pages/endpoints/0/args then check with page and per_page
curl http://YOUR-SITE/wp-json/wl/v1/posts/?per_page=1&page=2
Publish arguments for reference
We can define and publish these as arguments. This is not required but they are now in line with posts and pages
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'posts', [
'methods' => 'GET',
'callback' => 'wl_posts',
'args' => [
'page' => [
'description' => 'Current page',
'type' => "integer",
],
'per_page' => [
'description' => 'Items per page',
'type' => "integer",
]
],
]);
});
Fetch arguments
As get_posts has its own logic and it uses WP_Query in the end let's use WP_Query for the better.
function wl_posts() {
$args = [];
if (isset($_REQUEST['per_page'])) {
$args['posts_per_page'] = (int) $_REQUEST['per_page'];
}
if (isset($_REQUEST['page'])) {
$args['page'] = (int) $_REQUEST['page'];
}
$args['post_type'] = 'post';
$get_posts = new WP_Query;
$posts= $get_posts->query( $args );
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['featured_image']['thumbnail'] =
get_the_post_thumbnail_url($post->ID, 'thumbnail');
$i++;
}
return $data;
}
This is my code. I don't know what should I do now, because I'mm really confused in this problem.
in Controller for CSV Import
function import()
{
$this->load->library('csvreader');
$result = $this->csvreader->parse_file('./application/upload/financialloss.csv');
foreach($result as $value=>$key){
$date_report = date("Y-m-d H:i:s");
$handlingdate = $key['Handling Date'];
$handlingdate2 = strtotime($handlingdate);
$handlingdate3 = date('Y-m-d',$handlingdate2);
$nominal_awal = trim(preg_replace('/\s\s+/', ' ', str_replace("\n", " ", $key['Transactions Nominal'])));
$nominal = str_replace(",","", $key['Transactions Nominal']);
$nominal1 = str_replace(".","", $nominal);
$nominal2 = str_replace("Rp","", $nominal1);
$tblfinancialloss = array(
'handlingdate' => $handlingdate3,
'lossdate' => $key['Loss Date'],
'ticketid' => $key['Ticket ID'],
'reporteremail' => $key['Reporter Email'],
'reporterusername' => $key['Reporter Username'],
'transactionsfraud' => $key['Transactions Fraud'],
'transactionsfinancialloss' => $key['Transactions Financial Loss'],
'transactionsnominal' => $nominal2,
'cityofuser' => $key['City of User'],
'provinceofuser' => $key['Province of User'],
'transactionscategory' => $key['Transactions Category'],
'casecategory' => $key['Case Category'],
'sourcedata' => $key['Source Data'],
'linkphisingmedia' => $key['Link Phising Media'],
'notesloss' => $key['Notes'],
'dateinput' => $date_report,
'inputby' => "by ".$this->session->userdata('name')
);
if(empty($key['Loss Date'])){
$this->session->set_flashdata('msg','TES1');
redirect(base_url()."index.php/DashboardFinancial/AddFinancialLoss");
}
else{
$this->Csv_Import_model->insert($tblfinancialloss);
$this->session->set_flashdata('msgs',' data, uploaded today !');
}
}
//unlink('./assets/data.csv');
}
And this is My Model for CSV Import
function insert($data)
{
$this->dbfinanciallossandsave= $this->load->database('financiallossandsave', TRUE);
$insert_query1 = $this->dbfinanciallossandsave->insert_string('tblfinancialloss', $data);
$insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query1);
$date = date("Y-m-d");
$this->dbfinanciallossandsave->where('handlingdate <=', $date);
//$this->dbfinanciallossandsave->where('lossdate <=', $date);
$this->dbfinanciallossandsave->query($insert_query);
}
And my model for where condition can't work. Can you help me?
I've following the step from this website [https://www.webslesson.info/2018/04/how-to-import-excel-data-into-mysql-database-using-codeigniter.html#comment-form][1]
but when I trying to import the data, my database data still empty
My Import Function in Controller :
public function import()
{
if(isset($_FILES["file"]["name"]))
{
$path = $_FILES["file"]["tmp_name"];
$object = PHPExcel_IOFactory::load($path);
foreach($object->getWorksheetIterator() as $worksheet)
{
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
for($row=2; $row<=$highestRow; $row++)
{
$customer_name = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
$address = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
$city = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
$postal_code = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
$country = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
$data[] = array(
'CustomerName' => $customer_name,
'Address' => $address,
'City' => $city,
'PostalCode' => $postal_code,
'Country' => $country
);
}
}
$this->pppmodel->insert($data);
echo 'Data Imported successfully';
}
}
My model :
public function insert($data)
{
$this->db->insert('tbl_customer', $data);
}
}
Please help me
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,
......
This is my view file:
<?php
$data = array();
echo '<label class="control-label">Attribute Group Name</label>';
echo Select2::widget([
'name' => 'attribute_grp_name',
'data' => $attribute_group_name, // initial value
'options' => ['placeholder' => 'Please Enter Attribute Group Name', 'multiple' => true],
'pluginOptions' => [
'attribute_grp_name' => true,
'maximumInputLength' => 100,
],
]);
?>
In my view here selected data is not showing.
This is my controller for create and update function:
public function actionCreate()
{
$model = new AttributeSet();
$attribute_group = AttributeGroupLang::find()->select('*')->all();
$attribute_group_name = ArrayHelper::map($attribute_group, 'id_attribute_group', 'name');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('create', [
'model' => $model,
'attribute_group_name' => $attribute_group_name,
]);
}
}
This is update function:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$attribute_set_group_combination = AttributeSetGroupCombination::find()->where(['id_attribute_set' => $id])->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
if(!empty($post_array['attribute_grp_name'])){
AttributeSetGroupCombination::deleteAll('id_attribute_set = '.$id);
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('update', [
'model' => $model,
'attribute_set_group_combination' => $attribute_set_group_combination,
'attribute_group_name' => $this->getExistAttrSet($id),
]);
}
}
public function getExistAttrSet($id){
$query = new Query;
$query->select(['attribute_group_lang.name AS attribute_group_name','attribute_group_lang.id_attribute_group'])
->from('attribute_set_group_combination')
->join('LEFT OUTER JOIN', 'attribute_set', 'attribute_set.id_attribute_set =attribute_set_group_combination.id_attribute_set')
->join('LEFT OUTER JOIN', 'attribute_group_lang', 'attribute_group_lang.id_attribute_group =attribute_set_group_combination.id_attribute_group')
->where('attribute_set.id_attribute_set='.$id)
->all();
$command = $query->createCommand();
$model = $command->queryAll();
$data = array();
foreach ($model as $attrsetlist[]) {
$data = ArrayHelper::map($attrsetlist, 'id_attribute_group', 'attribute_group_name');
}
return $data;
}
Can anyone help me that how can i show the selected value in the multiple select field.
You just need to pass in model value:
<?php
echo kartik\select2\Select2::widget([
'name' => 'some_field_name',
// ----------------------
'value' => 'a',
//'value' => ['a', 'b'],
//'value' => $model->some_value,
// ----------------------
'data' => ['a'=>'a', 'b'=>'b', 'c'=>'c'],
'options' => ['placeholder' => 'Select menu items ...', ],
]);
?>