【问题标题】:Search bar with 2 foreign key in LaravelLaravel中带有2个外键的搜索栏
【发布时间】:2019-06-10 13:10:30
【问题描述】:

在文件夹book.index.blade.php 上的搜索栏中,我想搜索我的表authorsname 或我的表bookcases 的字段code

到目前为止,我知道在我的表 authors 的字段 name 上进行搜索。 我的问题是如何使用我的表 bookcases 的字段 code 进行请求?我不知道语法... 我是新手。

public function index(Request $req) 
{
    if ($req->search == "") {
          $books = Book::paginate(5);
          return view('admin.books.index', compact('books'));

    } else {

            $validated = $req->validate([
                'search' => 'alpha', 
            ]);

   $books = Book::whereHas('authors', function($query) use($req) {
            $query->where('name', 'like', '%' . $req->search . '%');
        })->paginate(5);
  return view('admin.books.index', compact('books'));
  }

}

【问题讨论】:

  • 你在寻找 SQL 或 Laravel 的答案吗?
  • @jarlh: Laravel,其实我不知道合成器...

标签: php sql laravel eloquent


【解决方案1】:

您可以在搜索中附加更多 whereHas 条件,如下所示:

$books = Book::whereHas('authors', function($query) use($req) {
        $query->where('name', 'like', '%' . $req->search . '%');
    })->whereHas('bookcases', function($query) {
        $query->where('code', 'like', '%' . $req->search . '%');
    })->paginate(5);

如果您想在书柜中搜索作者,您可以将第二个whereHas更改为orWhereHas。 p>

Obs:我建议你多了解一下 Laravel 雄辩的关联对象的方式。它有一个学习曲线,但肯定会在未来有所帮助。

【讨论】:

    【解决方案2】:

    看看这个Search on Eloquent Relationships

    否则,您也可以使用连接来执行此操作:

    Book::join('authors', 'books.fk_author', 'authors.id')
        ->join('bookcases', 'books.fk_bookcase', 'bookcases.id')
        ->where('authors.name', 'LIKE', '%'. $req->search . '%')
        ->select('authors.name', 'table.other_column', 'table.another_column')
        ->paginate(5);
    

    添加 orWhere 的提示如果您有多个搜索,请使用类似这样的内容,它更可靠:

    ->where(function ($query) {
    
        $query->orwhere('users.name', 'like', '%' . request('search') . '%')
            ->orWhere('users.id', 'like', '%' . request('search') . '%');
    })
    

    【讨论】:

      【解决方案3】:

      你可以试试这个:

      restructuring books table to:
      id
      title
      gender
      author_id
      bookcases_id
      
      
      public function index(Request $req) 
      {
         $s = $req->input('data');
          $data['search']=DB::table('books')
          ->leftjoin('authors', 'books.author_id', '=', 'authors.id')
          ->leftjoin('bookcases', 'books.bookcases_id', '=', 'bookcases.id')
          ->where('books.id','=',$s)
          -orWhere('bookcases.id','=',$s)
      
          return view('admin.books.index', $data);
      
      }
      

      希望这会有所帮助。这是查询生成器。只需导入use DB;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 1970-01-01
        • 2017-01-13
        • 1970-01-01
        • 1970-01-01
        • 2018-11-22
        • 2012-08-02
        相关资源
        最近更新 更多