php - 通过在 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);
但是当我点击 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)
那么我能做些什么来解决它呢?
解决方案
可以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);
推荐阅读
- asp.net - 如何防止在移动设备中发出一些 HTTP 请求?
- jquery - 在数据表jquery中重新加载页面后如何保持同一个表?
- javascript - 从对象数组中,获取特定属性
- docker - nginx SSL 证书名称与输入不匹配
- python-3.x - 数据操作 - Python
- multithreading - 对象地址突然变了
- netbeans - 如果安装了 nb-javac,NetBeans 插件会失败
- angular - 离子键盘。在输入字段中键入时自动完成闪烁
- wordpress - 航运类公式帮助:如果数量是1-3,收取X金额?
- typescript - 如何解释这个索引signatrue: let value: Dictionary
['foo']?