I just wonder how to convert the key of query result into numeric. This is my query result for the example:
$result = [{
"lat": "43289043208",
"lng": "-3890423802"
},...]
What I want is
$result = [{
0: "43289043208",
1: "-3890423802"
},...]
Any helps would be appreciated.
You can use array_values() method.
And iterate the result array
$newArray = [];
foreach(json_decode($result) as $res)
{
$newArray[] = array_values($res);
}
Finally, I use this, and it solved for now
$table_data = DB::table($table)->select(DB::raw("$lat_field as '0'"), DB::raw("$lng_field as '1'"))->get();
Related
I would like to perform a query in a table where the column is of json type and it contains array of objects, but only if a certain condition is met
This is my current code
$initial_results = DB::table('toys')->select('id','name')->where(['name' => 'sammy', 'email' => 'whateveremail']);
if($sk ==='yes') {
$results = $initial_results->>whereRaw('JSON_CONTAINS(`info`,\'{"sku":"B07V3SSLN11"}\')')
>whereRaw('JSON_CONTAINS(`info`,\'{"asin":"DTI-LALF3-EA18"}\')')
->get();
} else {
$results = $initial_results->get();
}
But I always get 0 result if the condition is met. In database, the info I want to query indeed exist. What is the proper way to query a json column which contains array of objects? See my example data
[
{
"sku": "DTI-LALF3-EA18",
"adId": 244077676726655,
"asin": "B07V3SSLN11",
"cost": 0,
},
{
"sku": "DTI-LALF3-EA18",
"adId": 242968940906362,
"asin": "B07V3SSLN11",
"cost": 10,
.........
................
I even tried
$initial_results = DB::table('toys')->select('id','name')->where(['name' => 'sammy', 'email' => 'whateveremail'])->->whereIn(DB::raw("JSON_EXTRACT(info, '$[*].asin')"),['B07V3SSLN11']);
Thanks in advance
You can query JSON columns by using the -> operator in your clause:
->where('info->asin', 'DTI-LALF3-EA18')
JSON Where Clauses Docs
I have this:
$merge = parents::with('children')->get();
which gives me:
[{
"id":1,
"parent_name":"Robert",
"children":[{
"id":5,"name":"Susan","dob":"2010-11-11"},
{"id":7,"name":"Tony","dob":"2014-12-10"}]
}]
I want to add age into children with expected output like this:
[{
"id":1,
"parent_name":"Robert",
"children":[{
"id":5,"name":"Susan","dob":"2010-11-11","age":"10"},
{"id":7,"name":"Tony","dob":"2014-12-10","age":"7"}]
}]
I tried this:
return $merge->map(function ($detail) {
$detail->age = \Carbon\Carbon::parse($detail->dob)->diffInYears();
return $detail;});
it gives me:
[{
"id":1,
"parent_name":"Robert",
"age":0,
"children":[{
"id":5,"name":"Susan","dob":"2010-11-11"},
{"id":7,"name":"Tony","dob":"2014-12-10"}]
}]
I tried:
return $merge->children->map(function ($detail) {
$detail->age = \Carbon\Carbon::parse($detail->dob)->diffInYears();
return $detail;});
It returns
Property [children] does not exist on this collection instance.
Is there any simple way to achieve my goal?
loop on each parent and its children and add new age property
$data = parents::with('children')->get();
$data->each(function($parent) {
$parent->children->each(function($child){
$child->age = \Carbon\Carbon::parse($child->dob)->diffInYears();
});
});
what I suggest and I think is better is to add an attribute to your Model like so:
class modelName extends Model{
protected $append = ['age'];
public function getAgeAttribute(){
return \Carbon\Carbon::parse($this->dob)->diffInYears();
}
}
Loop through parents and its children. Eventually calculate the age and put the value to array.
$merge->map(function ($mer) {
$mer->children->map(function ($child) {
$age = \Carbon\Carbon::parse($child->dob)->diffInYears();
$child->age = $age;
});
});
In my Laravel-5.8, I have these four queries accessng the same model:
$allLeaves = HrLeaveRequest::where('company_id', $userCompany)->whereYear('created_at', date('Y'))->count();
$pendingLeaves = HrLeaveRequest::where('leave_status', 1)->where('company_id', $userCompany)->whereYear('created_at', date('Y'))->count();
$rejectedLeaves = HrLeaveRequest::where('leave_status', 3)->where('company_id', $userCompany)->whereYear('created_at', date('Y'))->count();
$approvedLeaves = HrLeaveRequest::where('leave_status', 4)->where('company_id', $userCompany)->whereYear('created_at', date('Y'))->count();
How do I combine the four queries as one
something similar to this
$gender_unpublished_record = HrEmployee::selectRaw('count(gender_code) as count,gender_code, if (gender_code = 1, "Male", "Female") as gender')->whereNotIn('employee_code', $publishedgoals)->where('company_id', $userCompany)->where('hr_status', 0)->groupBy('gender_code')->get();
The one above only have 0 or 1. But what I want to achive takes care of everything in the table, leave_status as 1, 3 and 4
Thank you
in your Company Model you should have the relation:
public function HrLeaveRequests()
{
return $this->hasMany(HrLeaveRequest::class,'company_id');
}
now you could use withCount:
$value=Company::where('company_id',$userCompany)->withCount(['HrLeaveRequests as allLeaves'=>function($query){
$query ->whereYear('created_at', date('Y'));
},
'HrLeaveRequests as pendingLeaves'=>function($query){
$query->where('leave_status', 1)->whereYear('created_at', date('Y'));
},
'HrLeaveRequests as rejectedLeaves'=>function($query){
$query->where('leave_status', 3)->whereYear('created_at', date('Y'));
},
'HrLeaveRequests as approvedLeaves'=>function($query){
$query->where('leave_status', 4)->whereYear('created_at', date('Y'));
},
])->get();
i have problem when i want to change Get become Post.
when i use Get i can get the data
but when use post i cannot get the data please help me
i have change the web.php or routes become Post but i cannot get my data when i use post
i have change get become post in my web.php in my laravel. but the result not the same
this is my code in laravel
public function getHistoryEvent(Request $request) {
$consumer_data = array();
$consumer_data['consumer_key'] = request()->header('consumer-key');
$consumer_data['consumer_secret'] = request()->header('consumer-secret');
$consumer_data['consumer_nonce'] = request()->header('consumer-nonce');
$consumer_data['consumer_device_id'] = request()->header('consumer-device-id');
$consumer_data['consumer_url'] = __FUNCTION__;
$authController = new AppSettingController();
$authenticate = $authController->apiAuthenticate($consumer_data);
if($authenticate==1 || $authenticate==0){
$event = DB::table('u_history_events')
->select('u_history_events.history_events_id','u_history_events.events_image','u_history_events.events_description','u_history_events.date_create')
->where('u_history_events.events_id',$request->events_id)
->where('u_history_events.kode_customers',$request->kode_customer)
->get();
$responseData = array('success'=>'1', 'data'=>$event, 'message'=>"Success.");
}else{
$responseData = array('success'=>'0', 'data'=>array(), 'message'=>"Unauthenticated call.");
}
$orderResponse = json_encode($responseData);
print $orderResponse;
}
when use get i can get this data the result are :
{"success": "1",
"data": [
{"history_events_id": 2,
"events_image": "",
"events_description": "",
"date_create": "2019-05-11 10:59:01"
},
{
"history_events_id": 3,
"events_image": "",
"events_description": "",
"date_create": "2019-05-11 11:59:35"
}
}
but when i use post i only get
{"success":"1","data":[],"message":"Success."}
I am no Laravel expert, but according to the docs, looks like you have to explicitly define a route for the POST verb to your controller's method:
Route::post($uri, $callback);
Or according to Controllers docs:
// change <your path here> and <your method name> to your desired path and
// method names
Route::get('<your path here>', 'AppSettingController#<your method name>');
I also recommend you to read MDN's An overview of HTTP.
Assuming I've got a MongoDB instance with 2 collections - places and people.
A typical places document looks like:
{
"_id": "someID"
"name": "Broadway Center"
"url": "bc.example.net"
}
And a people document looks like:
{
"name": "Erin"
"place": DBRef("places", "someID")
"url": "bc.example.net/Erin"
}
Is there any way to validate the places DBRef of every document in the people collection?
There's no official/built-in method to test the validity of DBRefs, so the validation must be performed manually.
I wrote a small script - validateDBRefs.js:
var returnIdFunc = function(doc) { return doc._id; };
var allPlaceIds = db.places.find({}, {_id: 1} ).map(returnIdFunc);
var peopleWithInvalidRefs = db.people.find({"place.$id": {$nin: allPlaceIds}}).map(returnIdFunc);
print("Found the following documents with invalid DBRefs");
var length = peopleWithInvalidRefs.length;
for (var i = 0; i < length; i++) {
print(peopleWithInvalidRefs[i]);
}
That when run with:
mongo DB_NAME validateDBRefs.js
Will output:
Found the following documents with invalid DBRefs
513c4c25589446268f62f487
513c4c26589446268f62f48a
you could add a stored function for that. please note that the mongo documentation discourages the use of stored functions. You can read about it here
In essence you create a function:
db.system.js.save(
{
_id : "myAddFunction" ,
value : function (x, y){ return x + y; }
}
);
and once the function is created you can use it in your where clauses. So you could write a function that checks for the existence of the id in the dbRef.