Home > Software engineering >  laravel orderby tow column date and number
laravel orderby tow column date and number

Time:01-24

i have laravel relation and this is the model relation

public function get_journal_entry_lines()
{
    return $this->hasMany('App\Models\Journal_entry_line','user_id','id')->orderBy('date','asc')->orderBy('number','asc');
}

now the result come like this

| number|date        |
|-------|------------|
| 1     | 2022-01-01 | 
| 2     | 2022-01-01 | 
| 10    | 2022-01-01 | 
| 12    | 2022-01-01 | 
| 3     | 2022-01-01 |

and i need the data to be like this

| number|date        |
|-------|------------|
| 1     | 2022-01-01 | 
| 2     | 2022-01-01 | 
| 3     | 2022-01-01 | 
| 4     | 2022-01-01 | 
| 5     | 2022-01-01 |

and the relation already order by the date first then the number how can i do that thanks

CodePudding user response:

If you want to order by number first, it should be the first in your query.

return $this->hasMany(App\Models\Journal_entry_line::class, 'user_id', 'id')
    ->orderBy('number', 'ASC')
    ->orderBy('date', 'ASC');

If the number field is stored as string, you can use the following query :

return $this->hasMany(App\Models\Journal_entry_line::class, 'user_id', 'id')
    ->orderByRaw('number * 1 ASC')
    ->orderBy('date', 'ASC');
  • Related