简体   繁体   English

拉拉维尔。 如何按一个字段排序但首先获取具有另一个字段特定值的项目?

[英]Laravel. How to order by one field but first get items with specific value of another field?

I got a database with entries.我有一个包含条目的数据库。 Each entry have start date and state fields.每个条目都有开始日期和状态字段。 What I want to do is order entries by start date (done that) but first display ones that have state of 0 then the others (also ordered by start date) i'm also paginating data.我想要做的是按开始日期排序条目(完成),但首先显示状态为 0 的条目,然后显示其他条目(也按开始日期排序)我也在对数据进行分页。 Now order by date and pagination is pretty easy to do, but got no idea how to do that other thing.现在按日期和分页排序很容易做到,但不知道如何做其他事情。

The following build shows state=0 first, then ordered by date descending.以下构建首先显示state=0 ,然后按日期降序排列。 You can call either ->get() or ->paginate() .您可以调用->get()->paginate()

$builder = Model::where('something', '>', 'value')
    ->orderByRaw("IF(`state` = 0, 1, 0)  DESC")
    ->orderBy('date', 'DESC');

return $builder->paginate(15);

To order first ones by date ASC and the other ones by date DESC :要按date ASC订购第一个,然后按date DESC订购其他的:

$builder = Model::where('something', '>', 'value')
    ->orderByRaw("IF(`state` = 0, 1, 0)  DESC")
    ->orderByRaw("IF(`state` = 0, date, 1)  ASC")
    ->orderByRaw("IF(`state` = 0, 1, date)  DESC");

I just split ordering into 3 different conditions.我只是将订购分成 3 个不同的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel从集合中获取一个字段乘另一个字段值 - Laravel get one field by another field value from collection 如何在Laravel中将值从一个表单字段转移到另一个字段? - How to Transfer Value From One Form Field to Another Field in Laravel? 如何使用Doctrine 2按特定的一对多字段的值排序 - How to order by the value of a specific one to many field using Doctrine 2 如果期望值从laravel的下拉列表中选择,如何获得另一个字段? - How to get the another field if the expected value choose from dropdown in laravel? Laravel:如何仅当存在另一个特定字段时才需要该字段? - Laravel: How to make a field required only if another specific field exists? 获取挂钩函数中保存在“订单项”元数据中的自定义字段值 - Get a custom field value saved in Order items meta in a hooked function 如何选择具有max(选择字段)和另一(特定字段)的一行? - How to select one row with max(select field) and another (specific field)? 按一个自定义字段值排序,并使用Wordpress从另一个字段中选择帖子 - Order by One Custom Field Value and Select Posts From Another With Wordpress Laravel更新字段,带有另一个字段值 - Laravel Update field, with another field value Laravel根据另一个字段的值来验证该字段 - Laravel validate the field on the basis of value of another field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM