dongpan9760 2017-12-05 15:56
浏览 824
已采纳

Laravel按自定义日期字段排序

laravel orderBy id works fine with this function:

News::orderBy('id', 'desc')->paginate(20);

But I'm struggling to achieve this with a custom field.

My custom date field (sorting) is a jQuery UI datepicker field that fills a chosen date and it's in this format:

yy-mm-dd

so, if I choose from the datepicker let's say today it will be displayed as a 2017-12-05 and that saves in the database in a same format.

The reason for using this custom field is to add a old news articles, but in a different order.

I've tried to do this with:

News::orderBy('sorting', 'desc')->paginate(20);

but this error is displayed:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)

That column does exists in my database.

How can I order my created articles using my custom "sorting" date field in Laravel?

EDIT:

This is the function for the news lists:

public function newsList() {
        $news = News::orderBy('id', 'desc')->paginate(20);
        return view('news-list', compact('news'));
    }

As I mention before this works, but the idea is to order by a custom date field.

  • 写回答

1条回答 默认 最新

  • doutanghuan9595 2017-12-06 09:18
    关注

    OK, guys I've found the problem! :)

    I'll post it here, so it might be useful for someone else.

    I'm using the Laravel Translatable plugin. It has two models and two database for the articles. For an example "news" and "newsTranslation".

    So, when I want to use orderBy, I cannot order by fields records from the "newsTranslation". That will be only possible from the "news" table.

    This error was displayed

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sorting' in 'order clause' (SQL: select * from `news` order by `sorting` desc limit 20 offset 0)
    

    because the orderBy is trying to order the articles from the "news", not the "newsTranslation" and in my case that field wasn't available in the "news" table.

    I've fix that by creating a date custom field in the "news". Now everything works fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制