how to search a json array object in laravel - php

To search an object in JSON from MYSQL using Laravel you do this:
$parent = DB::table($this->table)
->where("right_children->parent", $firstParent)
->get();
The problem now is how I can go about searching objects in arrays
[
{ "parent": "fish",
"children": { "right": "nunu"}
},
{ "parent": "cat",
"children": {"right": "nonha"}
}
]
IF I want to find the name "nunu" how to I search it using laravel?
I tried this:
DB::table($this->table)
->whereJsonContains("right_children->children->right", $firstParent)
->get();
but no result, I know I am getting it wrong

Related

Laravel - Eloquent to Json, and then sortBy on json object not working

I have this json value that I want to be sorty but for some reason it's not working.
[
{
"id": 15028,
"order_id": 342,
"user_id": 3,
"status": "1",
"priority": "1",
"donedate": null,
"user": {
"id": 3,
"name": "Max"
}
},
{
"id": 15030,
"order_id": 341,
"user_id": 4,
"status": "2",
"priority": "1",
"donedate": null,
"user": {
"id": 4,
"name": "Jon"
}
}
]
This jSon structure is the result of Laravel eloquent object conversion using $object->toJson();
Now I keep this output in my Redis cache. What I want is to when the status and or priority of any order gets changed then I want to sort this jSon and store it back in Redis.
$order_list = collect($json_decoded_with_updated_values);
$order_list = $order_list->sortBy('status')->sortBy('priority');
Redis::set(\GuzzleHttp\json_encode($stich_list_in_collection));
Redis::set("orders_list", $orders_list, 302400);
However, I don't get a sort list. What I want to achieve is that, just like I would run two to three orderBy on an eloquent model like orderBy('status')->orderBy('priority')->get() .. I want to run the same two sortings on this json list.
Thanks in advance.
I figured it out. Actually we don't need to have a call-back as suggested by #brokedid. We can do it like following.
$order_list->sortBy('status')->sortBy('priority')->values()->all();
So I was missing the "->values()->all()" part. I hope if any one runs into the same problem in future, they can get a hint from this.
If you want to sort by multiple Fields, then you could try to sort with a callback-method:
$orderedList = $unorderedList->sortBy(function($item) {
return $item->priority.'-'.$item->status;
});
I wonder what's the result when you choose a different sort direction.
$order_list = $order_list->sortByDesc('status');

Laravel is returning objects with key:value instead of array of objects

I am trying to return Json response as an array of objects. But instead I got response as object of objects. I have condition_question table where I save question_id and condition_id. I want to retrieve all questions which contains particular condition id. And sort them by answers_number. I am new to Laravel, here is my code:
$conditionsIdArray = array($chosenConditionsIds);
$results = Question::whereIn('question_id', function ($query) use ($conditionsIdArray) {
$query->select('question_id')
->from('condition_question')
->whereIn('condition_id', $conditionsIdArray);
})->get()->sortByDesc('answers_number')->take(5);
return response()->json([
'questions' => $results
], 200);
I get response:
{
"questions": {
"0": {
"question_id": 842,
"question_title": "Qui tempora...",
"question_body": "Repellendus non sint...",
"image": "https://lorempixel.com/640/480/?18901",
"question_view_count": 17,
"votes_number": 9,
"answers_number": 9,
"id_user": 9930,
"created_at": "2019-09-07 09:59:05",
"updated_at": "2019-09-08 18:23:41"
},
"28": {
"question_id": 20346,
"question_title": "Quaerat facere...",
"question_body": "Repudiandae culpa ...",
"image": "https://lorempixel.com/640/480/?91963",
"question_view_count": 2,
"votes_number": 2,
"answers_number": 9,
"id_user": 3546,
"created_at": "2019-09-07 10:07:38",
"updated_at": "2019-09-07 10:07:38"
},etc
}
As you can see, I get object with object. I do not want key/value, just simple array of objects type Question.
I am struggling two days now, have tried some different stuff like toArray() but do not know how to solve it. Any help would be most welcome.
If you change the keys in an indexed array, it will believe it has an associate array, due to sorting the index is off. On the Laravel collection there is a values() method, which you can call there that reindex the collection.
return response()->json([
'questions' => $results->values()
], 200);

I want a more consolidate json format

I am getting json array after getting applying query logic.
[
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-20"
},
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "CRP",
"booking_date": "2018-05-20"
},
{
"id": "4",
"diag_name": "Seepz Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-21"
}
]
But i want a more justified json array written below.
[
{
"diag_name": "LT Diagnostics",
"test_name": [
{
"id": "3",
"name" : "Alk PO4"
},
{
"id": "3",
"name" : "CRP"
}
],
"booking_date": "2018-05-20"
},
{
"diag_name": "Seepz Diagnostics",
"test_name": [
{
"id": "4",
"name" : "Alk PO4"
}
],
"booking_date": "2018-05-21"
},
]
I am not getting it,How to do in php. I want a more consolidate json format.
Have you tried changing your SQL query to group by diag_name and booking_date? That would be the first step I’d employ to get the outer data.
Formatting the data in the nested manner you’re after could be a function of whatever record serializer you’re using — does it support nested JSON as a return type, or only flat JSON as your example return value shows?
If the record set -> JSON serializer only ever returns flat data, the comments above are correct that you will have to write your own formatter to change the shape of the JSON yourself...
The accepted answer of this other question may be of help:
Create multi-level JSON with PHP and MySQL
I'm not a PHP guy but this is a typical scenario to use functional programming by means of the monad Map.
Looking online I've found this article that could help you.
Changing datasource output is not always (seldom indeed) a viable option.
Enjoy coding

"Nested" array within db response using Codeigniter

I am trying to create a "nested" array within an object that I am returning from a database.
I can have more than one footnote per "thing".
This is what I am currently getting back:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnote_id": "1",
"footnote_text": " Footnote one"
}]
}
Here is the result I'm trying to generate:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnotes": [{
"footnote_id": "1",
"footnote_text": " Footnote one"
},
{
"footnote_id": "2",
"footnote_text": "Footnote two"
}]
}]
}
I have a footnotes table that has all kinds of footnotes (footnote_id and such).
I have a type table that has all kinds of things in it (type_id and such).
I also have a type_footnotes table that only has two columns: type_id and footnote_id
I'm not sure how to create the footnotes property of the response object - then display the results within that array.
Thank you for your time!
EDIT
Here is the query - I thought I had posted this as well. My apologies.
PHP
public function get_thing($type_id) {
$this->db->select('type.type_id, type.type, type.type_color');
$this->db->join('footnotes', 'footnotes.footnote_id, footnotes.footnote_text');
$this->db->join('type_footnotes, type_footnotes.type_id = type.type_id');
$query = $this->db->get_where('type', array('type.type_id' => $type_id), 1);
if ($query->num_rows() > 0) {
return $query->result();
}
}
Remove the limit, and post here what do you get as result :
$query = $this->db->get_where('type', array('type.type_id' => $type_id));

searching for a way to filter results by a field defined in another linked table using Doctrine and MongoDB

I need to find a way to filter results from a MongoDB database, based on fields found in the current table, and a field found in another table which is linked to the current table. Tables format:
{
"_id": ObjectId("51af256a0da4dd7804000007"),
"enddate": ISODate("2013-06-14T21:00:00.0Z"),
"main": false,
"name": "name 1",
"photo": "image-1.jpg",
"site": {
"$ref": "Sites",
"$id": ObjectId("51ac538c5f06751414bd9f98"),
"$db": "local"
},
"startdate": ISODate("2013-04-30T21:00:00.0Z")
}
{
"_id": ObjectId("51d3d5b9caa8213b12e92c5e"),
"sitefeatured": false,
"sitename": "a",
"sitephoto": "aa.jpg",
"siteurl": "aaaa.com/"
}
what i`m trying to do in ->where clause is to search in the string formed by this.name and this.site.sitename:
my problem is that i don't know / didn't find how to reference to property sitename of the site object
$entries = $dm
->getRepository($sTable)
->createQueryBuilder('o')
->where('function() { return ( (this.name + this.site.sitename).toLowerCase().indexOf("'.$_GET['sSearch'].'".toLowerCase()) !== -1 ) ? true : false }')
->sort($aColumns[$_GET['iSortCol_0']], $_GET['sSortDir_0'])
->limit($_GET['iDisplayLength'])
->skip($_GET['iDisplayStart'])
->getQuery()
->execute();
Is there anything like SQL join that i didn't came across, or what's the solution?

Categories