Using Multidimensional array in Laravel 8 Blade - php

I am trying to get a status count of some processes and tasks just like a to-do list tasks count.
My current database look like this SQL Database Structure
+----+---------+------------+-------------+---------+------------+---------------------+---------------------+
| id | user_id | list_id | name | records | status | created_at | updated_at |
+----+---------+------------+-------------+---------+------------+---------------------+---------------------+
| 1 | 1 | 8Kwvf8ikcV | 10 mails | 19 | On-Hold | 2021-03-11 07:56:17 | 2021-03-11 07:56:17 |
| 2 | 1 | a0pJRv4Zfc | temp_emails | 884 | On-Hold | 2021-03-11 08:02:13 | 2021-03-11 08:02:13 |
| 3 | 1 | xrgZZkrLFA | 10 mails | 19 | Processing | 2021-03-11 08:06:37 | 2021-03-11 08:06:37 |
| 4 | 1 | lDOX8p2sgU | 10 mails | 19 | Completed | 2021-03-11 08:53:51 | 2021-03-11 08:53:51 |
+----+---------+------------+-------------+---------+------------+---------------------+---------------------+
I am using
return $listStats = ListName::select([
DB::raw("status"),
DB::raw("COUNT(status) as count")
])->where('user_id', Auth::id())
->groupBy('status')
->get();
Query to get the database and its count.
Current laravel out put is showing as
[{"status":"Completed","count":1},{"status":"On-Hold","count":2},{"status":"Processing","count":1}]
My question is how can I get the count of completed status without using foreach loop?
Do I need to change my query? or can I simply use $listStats['Completed']['count'] ?

A foreach will be run at some point unless you use a join in the query to give an order and force a result with all possible status.
One easy solution would be
$StatCount[ //make sure to list all possible statuses here
"Completed" => 0,
"Processing" => 0,
"On-Hold" => 0,
];
foreach ($listStats as $listStat) {
$StatCount[$listStat->status] = $listStat->count
}
Now you can access your status counts like this $statCount['Completed']

Counting is a pretty lightweight job and it can be done on the fly easily. Instead of creating an extra query to count the records, collect the records and count them in Blade. It's a better idea because you will fetch the tasks anyway and no need to query them twice.
// In controller
$user = User::where('id', Auth::id())->with(['tasks' => function($query) {
$query->groupBy('status')
}])->get();
return view('viewName')->with(['user', $user]);
// In Blade
$user->tasks->Completed->count();

Related

How to show data based on date with column loop in one month in PHP MYSQL?

First, I have query like this:
SELECT
a.idpeg,
a.tanggal,
a.jam_masuk,
a.jam_pulang,
a.mode_absen
FROM
`tp_rekap_2018-01` a
WHERE
id_opd = '3'
AND periode = '2018-01'
And the result is:
+------+------------+-----------+------------+-----------+
|idpeg | tanggal | jam_masuk | jam_pulang | mode_absen|
+------+------------+-----------+------------+-----------+
|001 | 2018-01-01 | 07:01:01 | 14:01:01 | 1 |
|001 | 2018-01-02 | 08:01:01 | 15:01:01 | 1 |
|001 | 2018-01-03 | 09:01:01 | NULL | 1 |
|002 | 2018-01-01 | 10:01:01 | 16:01:01 | 1 |
|003 | 2018-01-01 | 11:01:01 | 17:01:01 | 1 |
|003 | 2018-01-02 | 12:01:01 | 18:01:01 | 1 |
+------+------------+-----------+------------+-----------+
my question is what I have to do when I want to show result of query with this format of table
Friend of mine suggest me to use the 'for' to loop the date/day and I was successfully generate day from day 1 to the last day of the month. But I can't get the loop script of date/day based on 'idpeg' from the left.
thx b4.
The correct way, i think is using PIVOTS. https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
There are many ways to do it. I can tell you what will be good solution in my opinion.
First of all, looks like you need some user system (make some user object in your PHP script and file or record in the database representing the user).
Then add the date records respectively to user id:
for (i = 0; i < idpeg.size; ++i)
user[a.idpeg[i]] = a.tanggal[i]
Then just use loop to print user data in columns as you did before.

rank query in laravel from one table data

At the moment it gets the races times in order but i want to combined the user_id column together, but to make sure when it groups it together it, the fastest recorded_time is kept.
Example of what i have so far from the query
User_id | race_id | recorded_time | stroke |
__________________________________________
2 | 2 | 10.03 | fly |
____________________________________________
1 | 3 | 12.98 | fly |
____________________________________________
2 3 13.58 | fly |
Here is the code that gives me that result
$query->where('race_history.stroke', '=', $stroke)
->orderBy('recorded_time', 'ASC')->get();
This is what i want it to return
User_id | race_id | recorded_time | stroke |
__________________________________________
2 | 2 | 10.03 | fly |
____________________________________________
1 | 3 | 12.98 | fly |
____________________________________________
I have tried the code bellow but it doesn't take the fastest record time
$query->where('stroke', '=', $stroke)
->orderBy('recorded_time', 'ASC')
->groupBy('user_id')->get();
But Instead produces this
User_id | race_id | recorded_time | stroke |
__________________________________________
1 | 3 | 12.98 | fly |
____________________________________________
2 | 3 | 13.58 | fly |
____________________________________________
So its grouping it by user_id BUT not taking it fastest recorded time
I have tried so many ways anyone can help this is a raw query to get what i want i would use this but the AND distance doesnt like this..
$total = DB::select(DB::raw('
SELECT *, min(recorded_time) as time
FROM race_history
WHERE stroke = "' . $stroke . '" AND distance="' . $distance . '"
GROUP BY user_id
ORDER BY min(recorded_time) ASC
'));
Here's raw query as I don't know laravel syntax
SELECT `user_id`, `race_id`, min(`recorded_time`) AS `recorded_time`, `stroke`
FROM `race_history`
WHERE `stroke` = 'fly'
GROUP BY `user_id`
ORDER BY `recorded_time` ASC

how to merge multiple rows with same id mysql

I'm new posting here but the community have been my best resource on my projects so far.
I'm a dumb/dummy Mysql "wanna be" and I'm in the middle of a project that is making me go mad.
I have a table from wordpress plugin buddypress that pairs meta_key and meta_values in order to create something akin to a taxonomy. My duty is to use these paired values to implement an advanced group search. Here is the original table:
--------------------------------------------
id | group_id | meta_key | meta_value
--------------------------------------------
1 | 1 | time-zone | Kwajalein
2 | 1 | playstyle | hardcore
3 | 1 | recruiting-status | Open
4 | 1 | ilvl | 115
5 | 1 | main-raid | Final Coil of Bahamut
6 | 1 | voicechat | fc.teamspeak3.com
etc....
Using a view I managed to create a more friendly searchable table for begginers :
gid| time-zone| playstyle | main-raid
--------------------------------------------
1 | | |
1 |Kwajalein | |
1 | | hardcore |
1 | | |
1 | | | Final Coil of Bahamut
1 | | |
And here is the view code:
SELECT distinct
group_id AS 'gid',
IF(meta_key='recruiting-status',meta_value,'') AS 'Recruitment',
IF(meta_key='server',meta_value,'') AS 'server',
IF(meta_key='time-zone',meta_value,'') AS 'tzone',
IF(meta_key='main-raid',meta_value,'') AS 'raid',
IF(meta_key='raid-days',meta_value,'') AS 'days',
IF(meta_key='playstyle',meta_value,'') AS 'playstyle',
IF(meta_key='raid-progression',meta_value,'') AS 'progression',
IF(meta_key='raid-time',meta_value,'') AS 'time',
IF(meta_key='tanker-spot',meta_value,'') AS 'tank',
IF(meta_key='healer-spot',meta_value,'') AS 'healer',
IF(meta_key='melee-dps-spot',meta_value,'') AS 'melee',
IF(meta_key='ranged-dps-spot',meta_value,'') AS 'ranged',
IF(meta_key='magic-dps-spot',meta_value,'') AS 'magic',
IF(meta_key='ilvl',meta_value,'') AS 'ilvl',
IF(meta_key='voicechat',meta_value,'') AS 'voice',
IF(meta_key='voicechatpass',meta_value,'') AS 'voicep',
FROM wpstatic_bp_groups_groupmeta
The point is, I need to merge that result (view) so all the group_id=1 or 2 or 3, etc stand in one single row, like this:
gid| time-zone| playstyle | main-raid
--------------------------------------------
1 |Kwajalein | hardcore | Final Coil of Bahamut
2 |SaoPaulo | regular | Second Coil of Bahamut
etc
Can anyone help me there?
Just surround your IFs in a MAX, or another aggregate function that will capture the non-empty strings (e.g., GROUP_CONCAT), and add a GROUP BY group_id add the end. For example,
SELECT
group_id AS gid,
MAX(IF(meta_key='recruiting-status',meta_value,'')) AS 'Recruitment',
MAX(IF(meta_key='server',meta_value,'')) AS 'server',
...
FROM wpstatic_bp_groups_groupmeta
GROUP BY group_id

PHP Unset index if no match

I have two tables that have these columns (I'm only showing revelant ones) :
tasks table
+----+------+
| id | todo |
+----+------+
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 0 |
| 5 | 1 |
+----+------+
entries table
+----+---------+---------+------+
| id | task_id | user_id | done |
+----+---------+---------+------+
| 1 | 3 | 1 | 1 |
| 2 | 5 | 2 | 1 |
| 3 | 5 | 1 | 1 |
| 4 | 2 | 1 | 0 |
+----+---------+---------+------+
I query these tables and only keep tasks where todo = 1, So I already have the data in a PHP object.
I then have two lists that the user can view : tasks that are to do, and archived (done), and tasks that are to do. I can generate the first list just fine, I'm looping through each task and entries if they have a matching task_id where user_id == $loggeduser && done == 1, and unsetting the index of those that don't match. However, I cannot find a logic to do this with my archive list, as I don't have entries to match. How do I loop my tasks and only keep those that are done, for the user? In this case, for the archive list for user 1, I'm excepting to only keep task id 3 and 5, and for user 2, only keep task id 2.
Thanks.
You can do all this using plain SQL (I suppose you're using some relational database).
This query gives you all the tasks "todo & done". To get the tasks "todo & not done", just change the "e.done = 1" to "e.done = 0". I'm sure you get the idea.
SELECT * FROM tasks t
INNER JOIN entries e ON t.id = e.task_id
AND e.user_id = [logged_user_id]
AND e.done = 1
WHERE
t.todo = 0

Finding a specific row in a PropelCollection

I have two tables. One for orders, and for their prefs. The tables look like this:
Order:
+----------+---------------+------------+
| orderID | orderNumber | clientID |
+----------+---------------+------------+
| 1 | abc123 | 2 |
| 2 | orderX | 7 |
| 3 | Joe9 | 2 |
| 4 | Order4 | 2 |
+----------+---------------+------------+
OrderPref
+----------+----------+-------------+
| orderID | prefID | prefValue |
+----------+----------+-------------+
| 1 | 1 | $100 |
| 1 | 2 | 123 |
| 1 | 3 | $35 |
| 2 | 1 | $600 |
| 2 | 2 | 876 |
| 2 | 3 | $44 |
+----------+----------+-------------+
What I want to is for each order, get the prefValue for a specific prefID. Currently, this is what I am doing:
$orders = OrdersQuery::create()->filterByClientID(2)->find();
foreach($orders as $o){
$prefs = $o->getOrderPrefs();
foreach($prefs as $p){
if($p->getPrefID() === 2){
echo $p->getPrefValue();
break;
}
}
}
This works, but there needs to be a better way to get the one row I want for each order without looping through all the prefs.
I know this doesn't work, but is there something like this?
$orders = OrdersQuery::create()->filterByClientID(2)->find();
foreach($orders as $o){
// This obviously doesn't work, so is there a short way to do this?
echo $o->getOrderPrefs()->filterByPrefID(2)->getPrefValue();
}
I was reading the docs and found a ->search() method, but I don't know how to use it.
$orders = OrdersQuery::create()->filterByClientID(2)->find();
foreach($orders as $o){
// How can I search for the row with the prefID I want?
echo $o->getOrderPrefs()->search()->getPrefValue();
}
Looking at some old Propel stuff I've written, I'm guessing something like:
$prefValue = OrdersQuery::create()->
joinOrderPref()->
where('OrderPref.prefID = ?', $prefId)->
filterByClientID($clientId)->
select('OrderPref.prefValue')->
find()
;
The issue is that you need to get a specific column (reference).
For these chainable queries, my view is that an auto-completing editor is pretty much mandatory - remembering the syntax is nigh-on impossible without it.
$prefValues = OrdersQuery::create()
->filterByClientId(2)
->joinOrderPref()
->withColumn('OrderPref.PrefValue', 'theValue')
// row above fetches ONLY the needed column from joined table and
// gives 'theValue' alias to it
->select('theValue')
->find();
With this you don't need to do any foreaches in PHP or do it in two steps.
About the ->select() part - it's there only to not get the fully bloated/hydrated object, but actually only an array (PropelArrayCollection to be precise) with the prefValue data you need.
I didn't test this live though, some syntax issues may arise.

Categories