Laravel输出模型按相关表列排序

时间:2018-10-19 12:47:20

标签: php laravel

我有这个查询过滤器,可以很好地查询出结果。例如,如果我需要查找作者名称为

的图书
Book::with('user', 'author')
    ->whereHas('author', function ($query) use($filters) { 
        $query->filter($filters);
     })->paginate(30);

但是事情是,如果我想按作者姓名订购书籍。我这种情况下什么也没有发生。

如何按作者姓名对书籍进行排序?

QueryFilter看起来像这样:

public function  __construct(Request $request) {
    $this->request = $request;
    $this->filterService = new FilterService();
}

public  function apply(Builder $builder) {
    $this->builder = $builder;
    foreach ($this->filters() as $name => $value) {
        if (method_exists($this, $name)) {
            call_user_func_array([$this, $name], array_filter([$value]));
        }
    }
    return $this->builder;
 }

 public function filters() {
     return $this->filterService->removeEmptyFieldsFromRequest($this->request);
 }

书本过滤器如下所示:

public function date($date) {
    return $this->builder->where('date', $date);
}

public function name_sort($order = 'asc') {
    return $this->builder->orderBy('name', $order);
}

1 个答案:

答案 0 :(得分:2)

您可以使用class join语句:

$books = Book::select('author.name AS author_name, countries.*')
  ->with('user')
  ->join('author', 'author.id', '=', 'book.author_id')
  ->orderBy('author.name', 'ASC')
  ->paginate(10);