I am Using Laravel
below mentioned is one of my db table columns
:
{ "body": { "age": { "dob": "1960-01-28", "age_in_years": 60, "dob_computed": false }, "gender": "female", "address": { "street": "No.341,KC De silvapura", "country": "LK", "locality": "Thimbirigaskatuwa", "postcode": "N/A" }, "comment": "", "id_type": "NID", "id_number": 869000000000, "last_name": "Dayawansa", "member_id": "", "first_name": "jj", "preferred_name": "", "contact_details": { "email": "", "phone_number_alternate": "", "phone_number_preferred": 716900761 }, "consent_obtained": true, "alternate_contacts_details": { "name": "", "email": "", "phone_alternate": "", "phone_preferred": "" } }, "meta": { "end_time": "2019-09-06", "start_time": "2019-09-06", "registered_by": "24f57630-a102-11ea-a415-23a06eeb8904" } }
my code is
My controller
:
$start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
$end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');
if i use created at it works
$participants = Participant::Where('created_at', '>=', $start_date)
->where('created_at', '<=', $end_date);
if is use start_time which is inside a array it returns empty
$participants = Participant::Where('data->meta->start_time', '>=', $start_date)
->where('data->meta->start_time', '<=', $end_date);
this isn't working
any suggestion where am i wrong ?
I have tested your code and I think you should change your date format and you should receive startDate and endDate in the same format form request as your column value has. Like, you have the start_time something like that "start_time": "2019-09-06" in your DB. So, use the same date format when you will compare it.
Test your code in this way.
$start_date = Carbon::parse('2019-09-06')->format('Y-m-d');
$end_date = Carbon::parse('2019-09-10')->format('Y-m-d');
You will get a response but if you use the below format then you will not receive any response.
$start_date = Carbon::parse('2019-09-06')->format('m/d/Y');
$end_date = Carbon::parse('2019-09-10')->format('m/d/Y');
Your query is fine. Just make sure that your json column name is data.
$participants = Participant::where('data->meta->start_time', '>=', $start_date)
->where('data->meta->start_time', '<=', $end_date)->get();
Use whereBetween method of elocuent:
$start_date = $request->has('startDate') ? $request->get('startDate') : Carbon::now()->subDays(30)->format('m/d/Y');
$end_date = $request->has('endDate') ? Carbon::parse($request->get('endDate'))->addDays(1)->format('m/d/Y') : Carbon::now()->addDays(1)->format('m/d/Y');
$participants = Participant::whereBetween('start_time', [$start_date , $end_date])->get(); // or ->first() ur choice.
to more details
Related
I have following JSON code in my database table
[
{
"indentifier": "category",
"name": "XXXXXXX",
"products": [
{
"indentifier": "childproduct",
"name": "XXXX",
"price": 15,
"sku": "+0094",
"factorynumber": "156670",
"unit": "50 Stk/Pck",
"kp": "50",
"discountCode": "V",
"from": "2020-01-01",
"to": "2099-01-01"
},
...
]
},
{
"indentifier": "category",
"name": "XXXXXXX",
"products": [
{
"indentifier": "childproduct",
"name": "XXXX",
"price": 29,
"sku": "+0104",
"factorynumber": "156680",
"unit": "50 Stk/Pck",
"kp": "50",
"discountCode": "V",
"from": "2020-01-01",
"to": "2099-01-01"
},
....
]
}
]
Now how I can implement for searching the sku in this JSON in "when" keyword? My following code is here:
$date = now()->toDateString();
if ($request->keyword != "") {
$keyword = $request->keyword;
} else {
$keyword = false;
}
$products = Product::whereJsonContains('catalogs', intval($request->catalog))
->whereDate('from', '<=', $date)
->whereDate('to', '>', $date)
->orderBy('category', 'ASC')
->orderBy('sort', 'ASC')
->where('active', 1)
})
->when(
$keyword,
function ($query, $keyword) use ($category) {
$query->where('sku', 'like', '%' . $keyword)
->orWhere('factorynumber', 'like', $keyword)
->orWhere('name', 'like', '%' . $keyword . '%')
->orWhereJsonContains('childs', ['products->sku' => $keyword])
->where('active', 1)
});
}
)->get();
The line with
->orWhereJsonContains('childs', ['products->sku' => $keyword])
will not work... what is the right syntax for the query? At moment there are 0 results if search for child sku field.
Thanks for helping
orWhereJsonContains() doesn't exist in Laravel, but whereJsonContains(), and it works with arrays and not the associative arrays. Also you have to make sure the data from json goes as the first argument, not the second like this:
whereJsonContains('table_column_name_with_json_in_it->json_value_key',$requiredValue)
In that case this query of yours:
->orWhereJsonContains('childs', ['products->sku' => $keyword])
Should be something like this:
->WhereJsonContains('product->sku', $sku)
I want to pass variables in for these values but I cant get them to go for example in user_id I want to pass the variable $userID
This is an example of the Body i'm using:
$body = '{
"data":
[
{
"user_id":$userID,
"type":"manual",
"date":"2021-01-30",
"duration":"150",
"jobcode_id":"15281216",
"notes":"This is a test of a manual time entry",
"customfields": {
"54138" : "IT Services",
"54136" : "Yes"
}
}
]
}'
I would use a double-quoted Here-String for that:
$userID = 'Alex'
$body = #"
{
"data": [{
"user_id": "$userID",
"type": "manual",
"date": "2021-01-30",
"duration": "150",
"jobcode_id": "15281216",
"notes": "This is a test of a manual time entry",
"customfields": {
"54138": "IT Services",
"54136": "Yes"
}
}]
}
"#
$body now contains:
{
"data": [{
"user_id": "Alex",
"type": "manual",
"date": "2021-01-30",
"duration": "150",
"jobcode_id": "15281216",
"notes": "This is a test of a manual time entry",
"customfields": {
"54138": "IT Services",
"54136": "Yes"
}
}]
}
The reason why $userID is not substituted for it's value in your example is because you are using a single quote (') character. PowerShell only substitutes when you use a double quote (") character.
This would give you the challenge that your data already contains double quotes. There Here string from Theo's answers works just fine but as a personal preference I would use a PowerShell hashtable to construct an object and convert it to Json using Convert-To-Json.
Example:
$userID = 'John'
$body = #{
"data" = ,#{
"user_id" = $userID;
"type" = "manual";
"date" = "2021-01-30";
"duration" = "150";
"jobcode_id" = "15281216";
"notes" = "This is a test of a manual time entry";
"customfield" = #{
"54138" = "IT Services";
"54136" = "Yes";
}
}
}
$body | ConvertTo-Json -Depth 3
Output:
{
"data": [
{
"notes": "This is a test of a manual time entry",
"customfield": {
"54138": "IT Services",
"54136": "Yes"
},
"duration": "150",
"type": "manual",
"date": "2021-01-30",
"jobcode_id": "15281216",
"user_id": "John"
}
]
}
EDIT: As robdy mentioned in the comments, the Depth parameter should be used (I've added it). A good explanation can be found here.
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})
Below is my JSON output received post the HttpGet successful execution.
{
"results": [{
"id": "1310760",
"type": "page",
"status": "current",
"title": "UniversalProfile Release Test",
"extensions": {
"position": 9
},
"_links": {
"webui": "/display/ds/UniversalProfile+Release+Test",
"tinyui": "/x/KAAU",
"self": "http:1310760"
},
"_expandable": {
"container": "/rest/api/space/ds",
"metadata": "",
"operations": "",
"children": "/rest/api/content/1310760/child",
"history": "/rest/api/content/1310760/history",
"ancestors": "",
"body": "",
"version": "",
"descendants": "/rest/api/content/1310760/descendant",
"space": "/rest/api/space/ds"
}
}],
"start": 0,
"limit": 25,
"size": 1,
"_links": {
"self": "UniversalProfile+Release+Test",
"base": "https://alim4azad.atlassian.net/wiki",
"context": "/wiki"
}
}
I am trying to extract the value for "id" but have been unsuccessful so far.
If your JSON is in the variable output in Javascript, it'd be :
output.results[0]["id"]
Like console.log(output.results[0]["id"]).
Your results section contains arrays. You want the first (0), and then the key id.
Looking at that resulting JSON hurts my brain.
Assuming you are using JavaScript, try this: output.results[0]['id']
Try This:
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("results");
JSONObject jsonObject1 = jsonArray.getJSONObject(0).getString("id");
Finally i found a solution for it . Below is the solution.
JSONArray results = getbodyPage.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
Long id = first.getLong("id"); // Get id of the found page
System.out.println("INFO : Found ID - " + id);
Thank you all for your valuable inputs.
i create a route with json_respone function.
the code:
/**
* #Route("/app/homec")
*/
public function HomeCatsAction(Request $request) {
$list = $this->getDoctrine()
->getRepository('AppBen2Bundle:HomeCategories')
->createQueryBuilder('e')
->getQuery()->getArrayResult();
$response = new JsonResponse($list);
$response->headers->set('Content-Type', 'application/json; charset=UTF-8');
$response->setStatusCode(200);
return $response;
}
the json show it's fine, but no prefix.
exp:
{
"id": 1,
"h_name": "test",
"h_des": "aaaaa",
"h_des_sell": "",
"h_des_full": "ssssss",
"h_info": "",
"pic": "",
"order": 2
}
i want that the response will be:
home_categories": [
{
"id": 1,
"h_name": "test",
"h_des": "aaaaa",
"h_des_sell": "",
"h_des_full": "ssssss",
"h_info": "",
"pic": "",
"order": 2
}
]
my current symfony 2 version is 2.6
i try many solutions but the same result
This should work:
$response = new JsonResponse(array('home_categories' => $list));