Get latest value in the group of records - php

I have this records table which I save weight, age and other biometrics in it.
Now I want to fetch the latest value of every biometric for every day so I can draw a chart.
The piece of code I'm using to fetch data from db before processing it is like the following:
Records::where("user",$uid)->
where("type", "biometric" )-> // record type
where("fk", $bid )-> //biometric type
where("datetime","<" ,$range->max)->
where("datetime",">" ,$range->min)->
groupBy( "datee" )->
selectRaw(" max(amount) as 'damount' , max(unit) as 'unit' , date(datetime) as 'datee' ")->
orderBy("datee","desc")->
get();
// !! Should change max values with the latest record in the group !!
Which datee is date of the day.
Say some users add more than one weight biometrics in a day so unit and damount should be the unit and value of lastest record of that day.
What can I use instead of max() to achieve this?
Thanks in advance,

Hope this helps:
Records::where("user",$uid)
->where(["type" => "biometric", "fk" => $bid])
->whereBetween(DB::raw("DATE('datetime')"), array($range->max, $range->min))
->groupBy("datetime")->latest()->get();

Can you try this
Records::where("user",$uid)
->where("type", "biometric")
->where("fk", $bid)
->where("datetime","<" ,$range->max)
->where("datetime",">" ,$range->min)
->latest()
->groupBy('datetime')
->get();

Related

Laravel 5.5 get multiple records which are recently updated

I am displaying multiple records which changed recently. In previous view there is a button that when I click, all records' kitchen_status becomes 1 from 0. After that if I add more records and change its kitchen_status to 1, then I only want to display latest records which has kitchen_status as 1. Here is what I had tried to get:
$orders = Order::where([
'kitchen_status' => 1,
'delivery_status' => 0,
])
->where('updated_at', \DB::raw("(select max(`updated_at`) from orders)"))
->get();
This works good, but when I add new record that kitchen_status with default value of 0, then none records display. I know that last ->where() is wrong but how can I make it right?
In short, I want to display all records with latest updated_at. Some little help will save my day.
I think this can help.
$orders = Order::where([
'kitchen_status' => 1,
'delivery_status' => 0,])->orderBy('update_at','DESC')->paginate(15);
I had tried this code and it works perfect but still I am looking short and pure method. Here is code that I found:
$orders = Order::select('orders.*')
->where('kitchen_status', 1)
->where('delivery_status', 0)
->where('updated_at', \DB::raw("(SELECT max(updated_at) FROM orders WHERE kitchen_status = 1 AND delivery_status = 0)"))
->get();
Is it good to check this answer as right answer or please add more answer.
You can limit the number of the most recent entries you want as
$orders = Order::where([
'kitchen_status' => 1,
'delivery_status' => 0,
])->orderBy('updated_at','DESC')->limit(20)
->get();
You can change the number to what you want.
I am not sure I understand the question 100% But I think what you are looking for is
Model::whereDate('updated_at', '>', \Carbon::now()->subHours(2));
Which will give you all the records where updated_at is older than 2 hours. The parameter can be changed to something else like 10 for hours etc, there is also a subDays(), subMonths() etc, if you need a bigger range.

Yii2 - find max based year in active record

I want to select maximum an field which is integer in my db.
So, First I try the orthodok's way :
SELECT max(a.nomor_surat) as max FROM request a
WHERE YEAR(a.tanggal_persetujuan) = YEAR(CURDATE())
Works. (In my case : max = 3)
Now, using AR,
Request::find()->select('max(nomor_surat) as max')->where(['YEAR(tanggal_persetujuan)' => 'YEAR(CURDATE())' ])->scalar();
I got max = 1,
How AR interpretatioin them correctly ?
Pleas Advice.
Thanks
Request::find()
->andWhere(['YEAR([[tanggal_persetujuan]])' => new \yii\db\Expression('YEAR(CURDATE())')])
->max('[[nomor_surat]]');

Insert into array based on items insert date

I am trying to make an array with posts in them, now, i need to insert the posts into the array based on their post date, eg if a post was posted on day 4 it will come after the post that was posted on day 5, so the newest posts gets added and displayed first, is there a good way to do this?
The easiest and not right method at all:
$sortedNews = []; //sorted news
foreach($newsArray as $news) {
$sortedNews[strtotime($news['date'])] = $news; //take date and switch to unix timestamp as key of value
}
krsort($sortedNews); //sort by key (reverse) new to old
The right way it's let your database sort it itself ORDER BY `date` DESC

Getting row which have latest time mysql codeigniter

I am trying to get a row which have latest created time,
Example, i have table with news_id, news_content, news_postedon. This table have 10 rows of data,
Now i want to pull row which have latest time of new_postedon,
I am using codeigniter,
I added below code,
function view_latestnews()
{
$this->db->join('sc_users', 'sc_users.user_id = sc_news.news_postedby');
$this->db->select_max('news_postedon');
return $this->db->get('sc_news')->row();
}
By using this function i got only value of news_posted on which is max like (stdClass Object ( [news_postedon] => 2015-04-12 21:28:21 )),
But i could not get value of news_content
How can i get complete row which have latest time of posted using codeigniter?
Thanks in advance
Try
function view_latestnews()
{
$this->db->join('sc_users', 'sc_users.user_id = sc_news.news_postedby');
$this->db->where('news_postedon = (SELECT max(news_postedon) FROM sc_news)');
return $this->db->get('sc_news')->row();
}

CodeIgniter Where_In select from different table?

i am trying to covert this query in active record
SELECT
crm_clients.id,
crm_clients.`moved_date`,
crm_clients.`contractor_id`
FROM
dev_pfands.`crm_clients`
WHERE crm_clients.`contractor_id` = 11
AND (
crm_clients.`status` = 9
OR crm_clients.`status` = 8
OR crm_clients.`status` = 7
)
AND crm_clients.id IN
(SELECT
crm_client_cheques.`client_id`
FROM
dev_pfands.`crm_client_cheques`)
AND crm_clients.`moved_date` BETWEEN '2014-08-01'
AND '2014-11-29 '
AND crm_clients.`contractor_id`<>''
GROUP BY crm_clients.`id
the section I'm having issue is
AND crm_clients.id IN
(SELECT
crm_client_cheques.client_id
FROM
dev_pfands.crm_client_cheques) `
i've tried the where_in method but overtime i try to include my attempt of $this ->db_pfands -> where('crm_client_cheques.client id' ,'id'); get hit with errors and have no idea how to get past this.
the original query should return 703 rows and when I've removed the part I'm stuck with it increase to 3045 so i need it to be included. any help is appreciated.
First of all you have a error in your code.
$this->db_pfands->where('crm_client_cheques.client id', 'id');
This will be
$this->db_pfands->where('crm_client_cheques.client_id', 'id');
You have to provide the right column name and as far i know database's column name have not contain any space.
Now I think this active record query will help you to get your result.
$query = $this->db->select('crm_clients.id, crm_clients.moved_date, crm_clients.contractor_id')
->where('moved_date BETWEEN "2014-08-01" AND "2014-11-29"')
->where('contractor_id', 'id')
->where_in('status', [9,8,7])
->from('crm_clients')
->join('crm_client_cheques', 'crm_client_cheques.client_id = crm_clients.id')
->group_by('id')
->get();
$result = $query->result();
May be you have change couple of names because they are in different database, but i believe you can do it.

Categories