[英]Sorting of columns by joining two tables in 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)
那么我能做些什么来解决它呢?
您可以将publisher_name
publishers.name
以便 mysql 可以找到别名列:
$books = Book::join('publishers','publishers.id','books.publisher_id')
->orderBy($sort,$direction)->selectRaw('books.*, publishers.name AS publisher_name')->paginate(5);
就像您在join
中所做的那样,您必须在$sort
、 table.column
中使用点符号。
除此之外......这将是编写此代码的更好方法:
publisher
关系添加到您的Book
Model。function publisher ()
{
return $this->belongsTo("App\Publisher");
}
books
关系添加到您的Publisher
Model。function books ()
{
return $this->hasMany("App\Book");
}
Book::with("publisher")
->orderby($sort, $direction)
->paginate(5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.