Laravel: upload multiple rows created from arrays - javascript

I'm building an application with Laravel which communicates with an OpenCPU server to perform some calculations. The OpenCPU server returns data in JSON format, which I then process to pull out the relevant information. This data returns a sku, retailer, date and sales. These are then posted to a controller using AJAX. Within this controller I then want to upload this data into the database by creating a new array of data to upload in one go. Each row should have a sku, retailer, date and sales. The date field in the database is called date, but called obs in the code.
OpenCPU returns JSON which is the parsed to a Javascript object using
var data = JSON.parse(output);
After logging to the Javascript console I get an array of the correct length, with the sales numbers.
The data is then sent to a Laravel controller via AJAX
$('#save').click(function(){
var id = $('#filter option:selected').text();
var json = $.ajax({
url: 'sales/' + id + '/update',
type: 'POST',
data: {
'sku': $('#sku').text(),
'retailer': $('#retailer').text(),
'obs': data.OBS,
'sales': data.Sales,
},
async: false
}).responseText;
var message = JSON.parse(json);
$('.flash').html(message).fadeIn(300).delay(2500).fadeOut(300);
});
In Laravel I then try to store the data in a MySQL database using the following
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$obs = Input::get('obs');
$sales = Input::get('sales');
foreach($obs as $key => $n ){
$arrayData[] = array(
'sku' => $sku,
'retailer' => $retailer,
'date' => $obs[$key]
'sales' => $sales[$key]
);
}
Chart::create($arrayData);
However the above code doesn't appear to work. The following code will create the correct number of rows in the database with the sku and retailer populated, but the sales figure is just the loop number, rather than the number of sales
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$dates = Input::get('obs');
$sales= Input::get('sales');
foreach(range(1, count($dates)) as $key){
DB::table('charts')->insert(
[
'sku' => $sku,
'retailer' => $retailer,
'date' => DateTime($obs[$key]),
'sales' => $sales[$key]
]
);
}
Given that the sku and retailer are a single input and repeated, I expect it's either an issue with passing the array to Laravel or the way in which I'm trying to access the elements in the 'obs' and 'sales' array

It looks like you have the right steps, get the inputs:
$sku = Input::get('sku');
$retailer = Input::get('retailer');
$dates = Input::get('obs');
$sales= Input::get('sales');
Buy now you try to forcibly insert them into the database. Why not use eloquent for database insertion: (Keep in mind you'd need to have a model for the charts table called Chart.php)
$chart = new Chart;
$chart->sku = $sku;
$chart->retailer = $retailer;
$chart->dates = $dates;
$chart->save();
That being said, I do realize that you're trying to pass arrays to the database, so that might take some experimentation. If you can't figure out what's (attempting) being passed to the database, you can always use:
die($variable);
To check what's up. Good luck!

Related

How to get specific key and value from a long json object while iterating it in node.js

I am trying to parse a csv file in node.js , i am able to parse the csv file and can print the content , the contents are coming as a from of a json object.Now my target is to iterate the json object and take out specific key and values from each block and use them in a Query which will do some DB operations.But the problem is while i am trying to iterate the json only first key and values of the first block is printed. Let me post the code what i have done
fs.createReadStream(path)
.pipe(csv.parse({headers:true ,ignoreEmpty : true}))
.on("error",(error) => {
throw error.message;
})
.on("data",function(data){
if(data && data!=={}){
Object.keys(data).forEach(function(k){
if(k==='name' || k==='Office'){
let selectQury = `select name,Office from myTable where name = ${data['name']} and Office
=${data[Office]};
db.query(selectQury,(err,res)=>{
if(err){
console.log('error',null);
This my json which i parse from the csv looks like
{
id:1,
name:"AS",
Office:"NJ"
........
ACTIVE: 1.
},
{
id:2,
name:"AKJS",
Office:"NK"
........
ACTIVE: 2.
}
so now what i want is in the select Query the parameters will be passed like
let selectQury = `select name,Office from myTable where name = "AS" and Office = "NJ";
in the first iteration
let selectQury = `select name,Office from myTable where name = "AKJS" and Office = "NK";
in the second iteration and so on as the csv grows.
I am not able to do it ,please help . Thanks in advance. I am new to node.js & tricky javascript operations.

Node JavaScript express JavaScript format data get from the sequlize query

I am using sequlize in express JavaScript framework.
const data = await db.Tour.findAll();
res.status(200).json(data)
If I do this I can nicely retrieve the data in the front-end vue JavaScript spa like this
{
tour_name:"Bali",
activities:[
{name:"Swimming"},
{name:"Beach vollyball"},
]
}
Above one is for retrieve the data for front-end.
If I need to get the data and make some changes in the controller before send them, I will raw: true
then I can get the same output in my controller. But the problem is raw: true is not going well with the
joins, so that point getting the data from the controller and make some changes to it is very hard.
I have to access so many nested objects to find the data I want. Is there a smarter way (there should be) to get the above format
from the controller without using the raw: true.
I hope there must be a nice way to pass that data object to some thing and convert to the format.
How do I achieve this?
In below code I had to retrieve a shops products images and its ids along with some other data like ratings, count etc.
In below code I had to retrieve a shop products images and its ids.
exports.filterShopListings = async (data) => {
return Db.sequelize.query("SELECT productImages, S.shopId, S.currency, S.mainImage, S.mainImageThumb, S.coverImage, S.coverImageThumb, S.name, S.location, S.approved, S.locationLatitude, CONCAT('"+process.env.QR_URL+"',S.qrCode) as qrCode, S.locationLongitude, COALESCE(productCount,0) as productCount, COALESCE(ratingCount,0) as ratingCount, COALESCE(ROUND(UR.ratingAvg,1) ,0) as ratings, COALESCE(shopFollowing,0) as followingCount FROM shops as S JOIN users U ON (U.userId=S.userId AND U.blocked='0') LEFT JOIN ( SELECT COUNT(*) as productCount, shopId, GROUP_CONCAT(mainImageThumb,'--',shopProductId) as productImages FROM shopProducts WHERE shopProducts.deleted='0' AND shopProducts.blocked='0' GROUP BY shopId) SP ON (SP.shopId=S.shopId) LEFT JOIN ( SELECT COUNT(*) as ratingCount, AVG(ratings) as ratingAvg, shopId FROM userRatings WHERE userRatings.blocked='0' AND userRatings.deleted='0' GROUP BY shopId ) UR ON (UR.shopId=S.shopId) LEFT JOIN ( SELECT COUNT(*) as shopFollowing, shopId FROM shopFollowings GROUP BY shopId) SF ON (SF.shopId=S.shopId) WHERE "+data.whereString+" HAVING "+data.havingString+" ORDER BY "+data.orderingParam+" "+data.orderingSort+" LIMIT "+data.skip+", "+data.take+" ",{ type: Sequelize.QueryTypes.SELECT})
.then( (shops) => {
shops = JSON.parse(JSON.stringify(shops));
shops.forEach( (shop) => {
//shop.productImagesTemp = shop.productImages;
shop.productImages = shopImagesFunc(shop.productImages);
});
return shops;
});
};
And The shopImagesFunc Code -
var shopImagesFunc = (productImages) => {
if(productImages ==null)
return [];
var images = (productImages.split(",").filter(Boolean));
var newImages = [];
images.forEach(image => {
let temp = image.split("--").filter(Boolean);
newImages.push({
shopProductId: parseInt(temp[1]),
mainImage: temp[0],
});
});
return newImages;
};
SQL Query is little complicated but creating a common function to format into required output would be very useful.

Convering json data to Java script array

i have code above which gets data from a database and then place in in json form to make it readable in java script.
the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],
"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();
Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];
Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];
in java script. Does Any one know how i can do this.
$query = mysqli_query($conn,"SELECT * FROM car_models");
// Loop the DB result
while(($result = mysqli_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){
// Create array for current user
$data[$result['Brand']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['Brand']][] = $result['Model'];
}
//json data
json_encode($data);
I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console
`
//json data
var brandAvailable =
console.log(brandAvailable);
"`

Overwriting Original Values In Collections

I am fetching data from database and storing it on $groups. It has different created_at for each entry.
I want to overwrite on created_at field in collection, just before returning it to the view, and have nice ->diffForHumans() version.
$groupsArray = $messages;
foreach($groupsArray as $key => $group) {
var_dump($groupsArray[$key]['created_at']); // works: 2015-10-17 21:55:46.000000'
var_dump($groupsArray[$key]['created_at']->diffForHumans()); // Error: A two digit month could not be found Data missing
$groupsArray[$key]['created_at'] = $groupsArray[$key]['created_at']->diffForHumans(); // Not Working
}
return $groupsArray->toJson();
If I change groupsArray = $messages->toArray();, the '// Error' bit of above chunk changes to Call to a member function diffForHumans() on string.
Eventually, I need to return it as json as it is ajax request. I want to overwrite on created_at, so I can use group[i]['created_at'] in javascript part in the view, after returning and get Carbon versions.
First, make sure 'created_at' is in your $dates array in your model.
Like described on http://laravel.com/docs/5.1/eloquent-mutators#date-mutators
Second, you can iterate and update over a collection by doing the following:
$messages->transform(function ($item, $key) {
$item->difference = $item->created_at->diffForHumans(); // 10 hrs ago
return $item;
});
$messages->toJson();
use &you can replace the original value !
foreach($groupsArray as &$key => &$group) {
var_dump($groupsArray[$key]['created_at']);
var_dump($groupsArray[$key]['created_at']->diffForHumans());
$groupsArray[$key]['created_at'] = $groupsArray[$key] ['created_at']->diffForHumans(); // Not Working
}

How to append database values to JSON data

I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]
database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
Below is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
Please help me here.
There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)

Categories