orderBy在一个表中不起作用

问题描述 投票:0回答:3

我想在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

php laravel
3个回答
0
投票

使用您提供的代码,我认为一切都应该正常工作。

用这几个代码很难理解那里发生了什么,所以这是你可以做的:

  • 在历史模型中,请确保您没有公共财产$timestamps设置为false
  • 仍然在历史模型中,添加protected $table = 'history'。 Laravel的默认行为将使Eloquent查看histories表,而不是history
  • 您的迁移从if(!Schema::hasTable('history'))开始,确保所有内容都正确更新。

希望能帮助到你。


1
投票

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();

0
投票

你为什么不尝试一些替代解决方案? 使用sortbyDesc方法,我从文档中确认它可用于您的Laravel版本(5.4)。

这是你的代码:

History::where('cus_id', $id)
    ->get()  
    ->sortbyDesc('updated_at');
© www.soinside.com 2019 - 2024. All rights reserved.