【发布时间】:2020-04-12 12:02:34
【问题描述】:
我有两个表书和出版商。 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)
那我该怎么解决呢?
【问题讨论】:
-
你能发布发布者迁移吗?
-
发布者迁移在“代码”下面给出 Schema::create('publishers', function (Blueprint $table) { $table->increments('id')->unsigned(); $table ->string('name'); $table->string('street'); $table->integer('number'); $table->bigInteger('zip'); $table->string('city '); $table->integer('country_id')->unsigned(); $table->foreign('country_id')->references('id')->on('countries'); $table-> string('license'); $table->timestamps(); }); }