首页 > 解决方案 > 通过在 Laravel 中连接两个表来对列进行排序

问题描述

我有两个表书籍和出版商。publisher_id 是publishers 表中的主键和books 表中的外键。在书籍的 index.blade.php 中,我想创建用于对书籍索引列进行排序的链接。这是我在其中创建链接的 index.blade.php 视图的那一部分。

<table class="table">
        <tr>
            <th><a href="{{ route('books-index',['sort' => 'name','direction' => 'asc']) }}">Name</a></th>
            <th><a href="{{ route('books-index',['sort' => 'published_date','direction' => 'asc']) }}">Published Date</a></th>
            <th><a href="{{ route('books-index',['sort' => 'publisher_name','direction' => 'asc']) }}">Publisher Name</a></th>
            <th>Category</th>
            <th>Author</th>

在 BooksController.php 中,我有我的索引方法,其中排序部分如下所示

public function index(Request $request) {
        $input = $request->all();
        $sort = 'created_at';
        $direction = 'desc';
        if(isset($input['sort'])){
            $sort = $input['sort'];
        }
        if(isset($input['direction'])){
            $direction = $input['direction'];
        }

        $books = Book::join('publishers','publishers.id','books.publisher_id')
                ->orderby($sort,$direction)->select('books.*')->paginate(5);

下面是我的书籍索引视图 index.blade.php 视图

但是当我点击 publisher_name 进行排序时,它给了我这样的错误。

QueryException in Connection.php line 770:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'publisher_name' in 'order clause' (SQL: select `books`.* from `books` inner join `publishers` on `publishers`.`id` = `books`.`publisher_id` order by `publisher_name` asc limit 5 offset 0)

那么我能做些什么来解决它呢?

标签: phpmysqllaravel

解决方案


可以publishers.name给取别名publisher_name,这样mysql就可以找到别名列:

$books = Book::join('publishers','publishers.id','books.publisher_id')
                ->orderBy($sort,$direction)->selectRaw('books.*, publishers.name AS publisher_name')->paginate(5);

推荐阅读