befreeforlife
befreeforlife

Reputation: 511

Use order by in pivot table data in Laravel's Eloquent ORM

I have three tables:

1) tasks;

2) visits;

3) task_visit;

Every visit can have 0 or several tasks. I need to sort tasks by a count of visits. For example, 1st task has 4 visits, 2nd - 10 etc.

In a similar case I had two tables:

1) doctors;

2) visits

I sort doctors by visits.

In StatVisit controller:

$tests = \App\Doctor::withCount(['visitsbydoctor' => function ($query) use ($a,$b){
  $query->whereBetween('date', array($a,$b));
}])->orderBy('visitsbydoctor_count', 'desc')->paginate(1000000);

In doctor model:

public function visitsbydoctor()
{
    return $this->hasMany(Visit::class);
}

How to rewrite this code in case of a pivot table? For Task model and StatVisit controller as in doctor case.

Upvotes: 0

Views: 284

Answers (2)

befreeforlife
befreeforlife

Reputation: 511

I found next work solution:

$tests1 = \App\Task::withCount(['taskvisit' => function ($query) use ($a,$b){
      $query->whereBetween('date', array($a,$b));
    }])->orderBy('taskvisit_count', 'desc')->paginate(1000000);


    public function taskvisit()
{
    return $this->belongsToMany(Visit::class)->withPivot('task_visit', 'visit_id');
}

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Use absolutely the same approach. withCount() works for many to many relationships as well:

Task::withCount('visits')->latest('visits_count')->get()

Upvotes: 1

Related Questions