1

I have many-to-many relationship users|pivot|task I need to order records by pivot table column(role) and by user table column(name). Ordering by pivot works, but order by users doesnt. Please give any advice how to fix this

Job model

public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class,'user_job')
            ->using(UserJob::class)
            ->withPivot('role')
            ->withTimestamps();
    }

User Model

 public function jobs(): BelongsToMany
    {
        return $this->belongsToMany(Job::class,'user_job')
            ->using(UserJob::class)
            ->withPivot('role')
            ->withTimestamps();
    }

Repository

return User::find($dto->getUserId())
            ->jobs()
            ->where($dto->getFilters())
            ->with('users')
            ->orderBy($dto->getSortBy(),$dto->getSortType()) // need to order by users.name
            ->paginate($dto->getPerPage());
randomdude
  • 173
  • 2
  • 7
  • Please see this link - https://stackoverflow.com/questions/14299945/how-to-sort-by-a-field-of-the-pivot-table-of-a-many-to-many-relationship-in-eloq – kewlashu Aug 06 '20 at 05:57
  • @kewlashu example shows how to order by pivot table, and I need to order by users table – randomdude Aug 06 '20 at 06:24
  • Does this answer your question? [Sorting a Laravel Collection by Many to Many Pivot Table Column](https://stackoverflow.com/questions/49928725/sorting-a-laravel-collection-by-many-to-many-pivot-table-column) – xNoJustice Aug 06 '20 at 18:52

0 Answers0