Mr.Junsu
Mr.Junsu

Reputation: 107

Eloquent Relationships in laravel

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 :(

Upvotes: 2

Views: 83

Answers (2)

Lijesh Shakya
Lijesh Shakya

Reputation: 2540

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

Upvotes: 2

danielpclin
danielpclin

Reputation: 31

Change your Task Model like this:

Model tasks

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

Upvotes: 2

Related Questions