2

i have three table as follows:

users:
id, fullname, phone ... 

tasks: 
id, user_id, title, description ...

tasks_state:
id, task_id, comment, rating, createa_at, updated_at

i am trying to use Relationships in laravel for order by updated_at in table tasks_state

Model tasks 

public function taskstate()
{
    return $this->hasOne(TaskState::class, 'task_id');
}

Model tasks_state

public function task()
{
    return $this->belongsTo(Tasks::class, 'id', 'taks_id');
}

I want the data returned sorted by field updated_at in table tasks_state when i use:

Tasks:with('taskstate')->get();

Look forward to your help :(

Mr.Junsu
  • 97
  • 1
  • 12
  • Possible duplicate of [Laravel Eloquent sort by relation table column](https://stackoverflow.com/questions/23530051/laravel-eloquent-sort-by-relation-table-column) – TheSalamov Jun 02 '18 at 02:51

2 Answers2

2

Change your Task Model like this:

Model tasks

public function taskstate()
{
    return $this->hasOne(TaskState::class, 'task_id')->orderBy('tasks_state.updated_at');
}
danielpclin
  • 31
  • 2
  • 3
2

You can use query builder within with clause and order the task state by updated_at

Tasks:with([
           'taskstate' => function($query){
               $query->orderBy('updated_at', 'desc');}
])->get();

If you want to retrieve everytime with updated_at in desc order, you can reference to Stack Overflow: Laravel default orderBy

Lizesh Shakya
  • 2,482
  • 2
  • 18
  • 42