[ How to write this query about "order by `update time`" in Laravel 5.2? ]
I am using Laravel 5.2.
How to write this query about "order by update time
"?
There are 2 tables,users
and articles
,they have a "one-to-many" relationship,
I would want to query user's name and his/her article titles,and order by article's update time
,
like this:
username article titles update time
Lily aaa-title-01;aaa-title-02;... 2016-04-20 12:00:00
Lucy bbb-title-01;bbb-title-02;... 2016-04-19 12:00:00
Jim ccc-title-01;ccc-title-02;... 2016-04-18 12:00:00
The update time
is the user's latest article's update time, for example:
The first one, username
is Lily, update time
is 2016-04-20 12:00:00
,it represents that Lily's latest article was updated at 2016-04-20 12:00:00
.
The second one,it represents that Lucy's latest article was updated at 2016-04-19 12:00:00
.
Lily's latest article is later than Lucy's,so, Lily is the first,Lucy is the second,and..,Jim is the third.
I writed the query like this:
$articles =User::whereHas('articles', function($query) {
$query->where('status', 1); //status is 1 or 0, 1 is published,0 is not published.
})->get();
This query could get the user and his/her articles,but could not order by update time
above,how to do it?
Answer 1
Just add orderBy
on the query and you should look good.
$articles =User::whereHas('articles', function($query) {
$query->where('status', 1)->orderBy('update_time', 'desc');
})->get();