Query to group by the contents of the field - php

I need help to make query to group by content of field. I have the following Database:
+----+--------------+-----------------+------------------------------+
| id | depart_kode | depart_task | value |
+----+--------------+-----------------+------------------------------+
| 1 | 001 | Create Profil | Some Value |
| 2 | 001.12 | Create Profil | Some Value |
| 3 | 001.452 | Create Profil | Some Value |
| 4 | 002.914 | Create Profil | Some Value |
| 5 | 002 | Create Profil | Some Value |
| 6 | 003 | Create Profil | Some Value |
+----+--------------+-----------------+------------------------------+
I need to make a query where I group by depart_kode and I should print by the first 3 digits like this in format json
"001":[
{
"depart_kode":"001,
and other
},
{
"depart_kode":"001.12"
},
],
"002":[
{
"depart_kode":"002"
}
]
something like that, most importantly they will be grouped in an array based on the first 3 numbers like 001.
and json just an example, which I want to split into an array based on the first 3 digits

Something like this?
$departs = [];
foreach ($sqlRows as $row) {
$departKey = substr($row['depart_kode'], 0, 3);
if (!array_key_exists($departKey, $departs)) {
$departs[$departKey] = [];
}
$departs[$departKey][] = $row['depart_kode'];
}
Working example.
references
substr - get a specific part of a string (first 3 chars in our example)
array_key_exists - checks if the key in an array exists

Related

how to get array in database column ? Laravel

I want to get array in database,it work in database query (my database i use postgrest) but not work in my project laravel.
Error message -> Undefined column: 7 ERROR: column sample1.text[1] does not exist
table sample1
___________________________________
| id | name | text[] |
|------+------+--------------------|
| 1 | aa | {xxx1,xxx2,xxx3} |
| 2 | bb | {xxx1,xxx2,xxx3} |
| 3 | cc | {xxx1,xxx2,xxx3} |
|______|______|____________________|
I need value
{
xxx1,
xxx1,
xxx1
}
my code
$search = DB::table("sample1")->select(array( 'sample1.text[1]'))->get();
return response()->json($search);
in my database query it work
SELECT "NSO_STAT_GIS"."BND_SET_STAT_TABLE"."MAPTB_CAT_SL_ID"[1] FROM "NSO_STAT_GIS"."BND_SET_STAT_TABLE"
$textsJson = DB::table("sample1")->select('text')->get();
$textArray = json_decode($textsJson);
https://laravel.com/docs/5.8/queries#selects

Show rows with a column partially matching a given parameter

Suppose I have a table named testdb which has the following values:
| Name | Phone |ID |
|------------------|------------|---|
| supriyo roy | 9038689236 | 2 |
| supriyo banerjee | 8013147879 | 3 |
| Alex ghosh | 8985855665 | 4 |
Now, I am performing a search by the name and the input given is just "supriyo" (no last name given).
The search result should show both the values:
| Name | Phone |ID |
|------------------|------------|---|
| supriyo roy | 9038689236 | 2 |
| supriyo banerjee | 8013147879 | 3 |
Is this possible to achieve using MySQL and php?
You are looking for LIKE:
select *
from your_table
where name like 'supriyo%';
Demo
Edit:
In php, use:
select *
from your_table
where name like '$name%';

Fetching Record Pattern From Database

I have a table like this in my database.
| id | yes_answer | no_answer |
| a01 | a05 | a04 |
| a03 | a16 | a32 |
| a04 | c01 | a05 |
| a05 | a06 | c06 |
| a06 | a08 | a09 |
| a08 | c03 | a09 |
| a09 | a03 | |
| a16 | a33 | a02 |
| a32 | c04 | a16 |
| a33 | c05 | |
As An Explanation :
1.id column represent an id of question. it is linked to another table on my database.
2.yes_answer column represent the next question (like a01) or conclusion (like c04) you get when you answer the question represented by id column with yes or TRUE or 1 value.
3.no_answer is generally the same as yes_answer column except that you get it when you answer question represented by id column with no, FALSE, 0 value.
4. Every id, yes_answer, no_answer is connected each other. The Result is A Pattern. When you Want to find a path that lead to answer c01 it will be like c05 -> a33,a16,a32,a03,a09,a06,a05,a01.
And Here I am Trying To Bactrack The Pattern From answer column that marked with c like c01 or c02 like above. And I've been able to bactrack only the beginning value of it Like (c05 -> a33) and the rest is blank.
Here is My Code
$sqlQueryYes="SELECT * FROM tbl_path_inference WHERE yes_answer='c05'";
$execQueryYes=mysql_query($sqlQueryYes);<br />
$queryStatus=mysql_num_rows($execQueyYes); //Getting Query Status<br />
if($queryStatus == 1) {
$getDataYes=mysql_fetch_array($execQueryYes);
$ansPath=$ansPath." ".$getDataYes['id'];
} else { // if cant find answer on column yes_answer try on no_answer
$sqlQueryNo="SELECT * FROM tbl_path_inference WHERE no_answer='c05'";
$execQueryNo=mysql_query($sqlQueryNo);
$getDataNo=mysql_fetch_array($execQueryNo);
$ansPath=$ansPath." ".$getDataNo;
}
Anyone Have Solution On It. Im Still working It Now.

How to map matched records returned from a join instead of separate rows

Scenario :
I have two tables, structured as following.
Table 1 : images
+--------+------------+
| img_id | img_name |
+--------+------------+
| 1 | image1.jpg |
| 2 | image2.jpg |
| 3 | image3.jpg |
+--------+------------+
Table 2 : image_tags
+---------+--------+----------+--------+--------+
| cord_id | img_id | tag_text | xcord | ycord |
+---------+--------+----------+--------+--------+
| 1 | 1 | Tag1 | 28.1 | 30.4 |
| 2 | 1 | Test Tag | 23.4 | 4.5 |
+---------+--------+----------+--------+--------+
Now i want the images along with their tags which is quite simple using the left join
SELECT img_id, img_name,tag_text, xcord,ycord FROM images t1 LEFT JOIN image_tags t2 ON t1.id=t2.id
This query results in the following data set
+--------+------------+----------+--------+--------+
| img_id | img_name | tag_text | xcord | ycord |
+--------+------------+----------+--------+--------+
| 1 | image1.jpg | Tag1 | 28.1 | 30.4 |
| 1 | image1.jpg | Test Tag | 23.4 | 4.5 |
| 2 | image2.jpg | NULL | NULL | NULL |
| 3 | image3.jpg | NULL | NULL | NULL |
+--------+------------+----------+--------+--------+
Problem :
Now using PHP (or MYSQL if possible), i want the results from the image_tags table to be concatenated with each row in form of an array.
So that when i loop through the records in Angular, i have images along with their tags in form of an array instead of two separate rows as you can see the first two rows in the result set.
Desired result example,
{
cord_id : 1,
img_id : 1,
tags : [{
tag_text : "Tag1",
xcord : 28.1,
ycord : 30.4,
},{
tag_text : "Test Tag",
xcord : 23.4,
ycord : 4.5,
}
]
}
I have studied about map() function in PHP but unable to achieve this.
Note: I am using Codeigniter, so if that has some relevant support to achieve this, that would also work for me.
Any help would be highly appreciated. Thanks
It is possible to do it with just one query.
Since you have a unique ID you can use it as an index for your array.
$images = array();
foreach($queryResults as $result){
if(!isset($images[$result['img_id']])){
$images[$result['img_id']] = array();
$images[$result['img_id']]['cord_id'] = $result['cord_id'];
$images[$result['img_id']]['img_id'] = $result['img_id'];
$images[$result['img_id']]['tags'] = array();
}
$tag = array(
'tag_text'=>$result['tag_text'],
'xcord'=> $result['xcord'],
'ycord'=> $result['ycord']
);
$images[$result['img_id']]['tags'][] = $tag;
}

Finding sum through eager loading

I've a table schema as follows:
+----+---------------+------------+--------+
| id | crowd_fund_id | email | amount |
+----+---------------+------------+--------+
| 1 | 11 | jj#xx.com | 200 |
| 2 | 11 | sd#ff.com | 250 |
| 3 | 12 | jj#xx.com | 150 |
| 4 | 12 | abc#cc.com | 230 |
+----+---------------+------------+--------+
And a Entries table:
+----+---------+----------+------+
| id | user_id | crowd_id | name |
+----+---------+----------+------+
| 1 | 6 | 11 | Abc |
| 2 | 6 | 12 | Xyc |
| 3 | 8 | 18 | ijn |
+----+---------+----------+------+
In the Backer's Model
public function entry()
{
return $this->belongsTo('App\Entries', 'crowd_fund_id', 'crowd_id');
}
and in the Controller I've called:
$var = Backers::with('entry')->where('email', $user->email)->get();
This works fine. Now I wanted to get the sum also through the eager loading.
That means I need to call something like
Backers::with('entry')->with('sum')->where('email', $user->email)->get();
The sum will calculate the total of all the amount where crowd_fund_id is equal to the raw where email = $user->email.
That means when I call
Backers::with('entry')->with('sum')->where('email', $user->email)->get();
I should be getting :
1 raw for the backer's details with crowd_fund_id
1 raw for the corresponding entry where crowd_fund_id = crowd_id
1 sum of all amount where crowd_fund_id = crowd_fund_id from the backer's details.
How can I get this?
Could you try something along these lines (in your Backers model):
public function backersSum()
{
return $this->hasOne('App\Backer')
->selectRaw('crowd_fund_id, sum(amount) as aggregate')
->groupBy('crowd_fund_id');
}
Doing it this way allows you to eager load it like any relationship. Then you could do something like this to access it:
public function getBackersSumAttribute()
{
if ( ! $this->relationLoaded('backersSum'))
$this->load('backersSum');
$related = $this->getRelation('backersSum');
return ($related) ? (int) $related->aggregate : 0;
}

Categories