我有一个非常简单的解决方案,但我不喜欢它。那么,我该怎么办?
我的数据库:
--------------------------------------
id name view created_at
--------------------------------------
1 one 9 2021-01-13 12:34:22
2 two 8 2021-01-15 10:23:02
3 three 23 2021-01-15 20:55:17
4 forth 15 2021-01-16 12:34:22
5 fifth 0 2021-01-19 10:37:02
我想像这样排序并获取我的数据:
--------------------------------------
id name view created_at
--------------------------------------
5 fifth 0 2021-01-19 10:37:02
3 three 23 2021-01-15 20:55:17
4 forth 15 2021-01-16 12:34:22
1 one 9 2021-01-13 12:34:22
2 two 8 2021-01-15 10:23:02
我当前的代码是:
$today = '2021-01-19'; //this date will calculate in daily. Not absolute date!
$firstarray = Product::where('created_at', 'LIKE', $today . '%')->get();
$secondarray=Product::orderBy('viewer', 'DESC')->get();
$data = array_merge($firstarray, $secondarray);
return $data;
如果今天的日期是硬编码的,它将是:
$today = '2021-01-19'; //this date will calculate in daily. Not absolute date!
$data = Product::orderBy(DB::raw('FIELD(created_at, LIKE $today . "%")'),'DESC')
->orderBy('view', 'desc')->get();
return $data;
我需要一个动态查询来按今天的日期排序,然后按
view
值 DESC 排序。
我正在使用 Laravel 6。
我想您首先需要今天的记录,然后按视图排序其余的记录。所以在这种情况下,您可以将结果排序为
Product::orderByRaw("date_format(created_at ,'%Y-%m-%d') = ? desc, view desc", [$today])
->get();
你的问题不清楚!如果这是我理解的方式,那就是解决方案。
$data = Product::whereDate('created_at', now())->orderBy('view','desc')->get();