【问题标题】:Order by relationship with pagination laravel eloquent按与分页关系排序 laravel eloquent
【发布时间】:2021-07-14 15:59:34
【问题描述】:

我有下面的关系,一个应用属于一个用户。

用户表

ID | Name
 1 | Danny
 2 | Mark

应用程序表

ID | user_id
 1 | 1
 2 | 2

Application.php

public function user()
{
    return $this->belongsTo(User::class);
}

我正在尝试按用户名对应用程序进行排序并对结果进行分页。我尝试了下面的代码,分页正在工作,但 order by 没有任何效果。

    $query = Application::query();

    $query = $query->with(['user' => function ($query){
            $query->orderBy('name', 'DESC');
    }]);

    $query = $query->paginate(10);

【问题讨论】:

  • with()paginate()的解决方案吗?

标签: laravel eloquent


【解决方案1】:

尝试使用内连接并按关系列排序:

$applications = Application::select('*')
    ->join('authors', 'applications.user_id', '=', 'users.id')
    ->orderBy('authors.name', 'DESC')
    ->paginate(10);

【讨论】:

  • 没有加入?
【解决方案2】:

试试这个:

Application::join('users', 'applications.user_id', '=', 'users.id')
    ->orderBy('users.name','desc')
    ->with('users')
    ->get();

【讨论】:

  • 没有加入?
猜你喜欢
  • 2021-01-25
  • 2014-06-25
  • 1970-01-01
  • 2019-09-16
  • 2017-08-22
  • 2016-09-26
  • 2016-07-27
  • 1970-01-01
  • 2016-06-21
相关资源
最近更新 更多