我想在Laravel中使用orderby来对数据进行排序。这是我的代码:
History::where('cus_id', $id)
->orderBy('updated_at', 'DESC')
->get();
历史表迁移
public function up()
{
if(!Schema::hasTable('history')) {
Schema::create('history', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255)->nullable();
$table->string('cus_id', 40)->nullable();
$table->string('activity', 255)->nullable();
$table->string('remark_id', 4)->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->string('note', 255)->nullable();
$table->timestamps();
});
}
}
结果不符合orderby
使用您提供的代码,我认为一切都应该正常工作。
用这几个代码很难理解那里发生了什么,所以这是你可以做的:
$timestamps
设置为false
protected $table = 'history'
。 Laravel的默认行为将使Eloquent查看histories
表,而不是history
。if(!Schema::hasTable('history'))
开始,确保所有内容都正确更新。希望能帮助到你。
orderBy方法允许您按给定列对查询结果进行排序。 orderBy方法的第一个参数应该是您要排序的列,而第二个参数控制排序的方向,可以是asc或desc =>
这是你的解决方案=>
$users = DB::table('history')
->where(['cus_id'=>$id])
->orderBy('updated_at', 'desc')
->get();
如果你正在使用模型,那么,
History::where('cus_id',$id)->orderBy('updated_at','desc')->get();
你为什么不尝试一些替代解决方案?
使用sortbyDesc
方法,我从文档中确认它可用于您的Laravel版本(5.4)。
这是你的代码:
History::where('cus_id', $id)
->get()
->sortbyDesc('updated_at');