Loop parameters through a query collection and then merge them (Laravel 8) - php

I got a few parameters in the url that I want to loop into a Laravel where query. After doing that I want to merge them into 1 collection and without duplicates.
This is what I have written already:
foreach($request->query() as $key => $query){
$guides[] = SupportGuideTranslation::where($key, $query)->get();
}
These are my parameters:
?active=1&language_id=2

Your current code executes one query per parameter/condition. You could do:
$query = SupportGuideTranslation::query();
foreach($request->query() as $key => $value){
$query->where($key, $value);
}
$guides = $query->get();
I would also advise you to check that the parameter actually exists on the table before adding it to the query. If I make a request with active=1&non_existing_column=2 your code would throw an error.

$guides = new Collection;
foreach($request->query() as $key => $value){
if($guides->isEmpty()){
$guides = SupportGuideTranslation::where($key, $value)->get();
}
else{
$guides = $guides->toBase()->merge(SupportGuideTranslation::where($key, $value)->get());
}
}
$guides = $guides->unique();

where() can take an array. So you don't necessarily need to loop:
SupportGuideTranslation::where($request->query())->get();
If that doesn't work for you and you have to loop over the query params, that might help:
$guides = new Collection;
foreach($request->query() as $key => $query){
$guides = $guides->merge(SupportGuideTranslation::where($key, $query)->get());
}
$guides = $guides->unique();

Related

Getting multiple fields from database to an array

I wrote an api call in my Symfony project that returns all fields from my entity with the query defined below..
Now, I need to define just three fields like 'id', 'name', 'value' and to pull values from that fields that are currently stored in a database.
public function getChartData() {
$myResults = $this->getMyRepository()
->createQueryBuilder('s')
->groupBy('s.totalCollected')
->orderBy('s.id', 'ASC')
->getQuery()
->getArrayResult();
$result = array("data" => array());
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
}
The problem is it return just totalCollected field.
One of errors are Call to a member function getId() on array and so on, and I can't figure out a way to pull data from db...
I cannot see in your code where $schoolResult come from but lets guess it string key of some sort.
Notice you trying to set 3 value on the same key so only the last one remains.
Look at:
$a = array();
$a["key"] = 4;
$a["key"] = 6;
It is simple to see that $a["key"] will contains 6 and not 4 or both.
When you do:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
You override the data in $result['data'][$schoolResult] therefor only try totalCollected is there as the last one to set.
In order to fix that you can use:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult]["id] = $label["id"];
$result['data'][$schoolResult]["name"] = $label["name"];
$result['data'][$schoolResult]["totalCollected"] = $label["totalCollected"];
}
Hope that helps!

Query from query result in foreach

so i have this function
public function GetNearAirport($adr)
{
$acftrange = $this->GetAcftAdr($adr);
$too = array();
foreach ($acftrange as $key) {
$result = $this->GetNearRange($adr,$key->range);
}
The $acftrange give me some rows, and i need to get a new result for each row of $acftrange. But i need all results in one array So I can insert into the html table. Sorry for my english. In foreach the $key->range is a condition for the query to be made.
I assume getNearRange() returns an array. Use array_merge to append $result to $too
foreach ($acftrange as $key) {
$result = $this->GetNearRange($adr,$key->range);
$too = array_merge($too, $result);
}

Pass array in the CodeIgniter query

I want to pass an array in codeigniter query. Below is my code.
Controller
foreach($array as $values) {
$array_values = $values['download_subcategory_name'];
}
$this->data['get_downloads_content'] = $this->my_model->get_downloads_content($array_values );
Model
public function get_downloads_content($array_values ){
$this->db->select('*');
$this->db->from('my_table');
$this->db->where_in('download_subcategory_name', $array_values );
$this->db->order_by('download_id', 'ASC');
$query = $this->db->get();
return $query->result();
}
My problem is query showing results for only last value of array instead of all array values.
Please help.
Just need little changes within foreach
$array_values = array();
foreach($array as $values) {
$array_values[] = $values['download_subcategory_name'];
^^^
}
OR
$array_values = array();
foreach($array as $key => $values) {
$array_values[$key] = $values['download_subcategory_name'];
^^^^^^
}
Within your code it's storing only the last value from the foreach loop thats why it only gets the single value stored within it.

How to change a php array

Simple question to which I don't have an answer.
How can I change my array from this:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
to this:
[{"sku":"6","buyers":"7","base":"8"}]
I have three queries for three different database tables:
$sku = DB::table('mapiranje')->select(DB::raw('count(*) as sku'))
->where('mate_fk', '=', NULL)
->get();
$kupac = DB::table('mapkupci')->select(DB::raw('count(*) as buyers'))
->where('kupci_fk', '=', NULL)
->get();
$base = DB::table('dist_base')->select(DB::raw('count(*) as base'))
->where('base_fk', '=', NULL)
->get();
now each returns:
[{"sku":"6"}]
[{"buyers":"6"}]
[{"base":"6"}]
I have used merge_array to make a single array, but I get:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
what I want is:
[{"sku":"6","buyers":"7", "base":"8"}]
Refactor your code according to right Laravel way:
$result = [
'sku' => DB::table('mapiranje')->whereNull('mate_fk')->count(),
'buyers' => DB::table('mapkupci')->whereNull('kupci_fk')->count(),
'base' => DB::table('dist_base')->whereNull('base_fk')->count()
];
$result = [];
foreach($input as $oneInputRow) {
$result[$oneInputRow[0]] = $oneInputRow[1];
}
$target = array();
$start = array(array("sku"=>"6"), "buyers"=>"7"), "base"=>"8"));
foreach($start as $sub){
foreach($sub as $key => $val){
$target[$key] = $val;
}
}
Not shure if laravel provides any special syntax, but just with php I'd do it as above.
Basicly you loop over the start-array. In that you loop over every array to get the key/val combination and put that into the target-array.
For the second loop there would be other ways if you only have one entry in every secondary array.
Please try below code
$dd = '[{"sku":"6"},{"buyers":"7"},{"base":"8"}]';
$data = json_decode($dd,true);
$result = array();
foreach($data as $key=>$value){
foreach($value as $key1=>$value1){
$result[$key1] = $value1;
}
}
echo json_encode($result); //this will print your required format result

Codeigniter Where Or from previous Query

I have the following query:
$this->db->where('user_id', $this->session->userdata('user_id'));
$this->db->where('barcode != ""');
$codes = $this->db->get('acquisti')->result();
return $codes;
This produces a result (varius fields) that can show one or more records, I need to tell Codeigniter to show FROM ANOTHER TABLE the results where "barcode" is one of the record found above.
I tried this:
$this->db->where('user_id', $this->session->userdata('user_id'));
$this->db->where('barcode != ""');
$codes = $this->db->get('acquisti')->result();
foreach ($codes as $key => $value) {
$this->db->where('IRSC', $value->barcode);
return $this->db->get('rendiconti_agosto')->result();
}
But this returns only ONE result even if the $code is actually more than one.
Any hint?
Try to catch them in array and then return them like
foreach ($codes as $key => $value) {
$this->db->where('IRSC', $value->barcode);
$result_arr[] = $this->db->get('rendiconti_agosto')->result();
}
return $result_arr;
In your code you are return for the first time of loop so the loop will terminated at first and then results only the first result that you get.
Try this. You can do it without loop.
$this->db->select("*");
$this->db->from("acquisti a");
$this->db->join("rendiconti_agosto ra","ra.IRSC = a.barcode ");
$this->db->where('a.user_id', $this->session->userdata('user_id'));
$this->db->where('a.barcode <> ""');
$res = $this->db->get();
return $res->result_array();

Categories