【问题标题】:Laravel Select2 SearchLaravel Select2 搜索
【发布时间】:2019-03-11 10:12:59
【问题描述】:

我使用了 select2 jquery 插件,但我无法搜索我想要输出的数据。 我一直在尝试在我的数据库中搜索一本书的名称,该名称应该是可用的,并且与我目前所在的公司分支机构一起。我正在为此处理 2 个表。

书籍

book_type_id [1, 2]

status ['Available', 'Available']

book_type

id [1, 2] name ['Book 1', 'Book 2']

public function get_available_book_type(Request $request){
    $employee = employee::where('id', Auth::user()->emp_id)->first();
    $bt = books::with('book_type')->where('branch_id', $employee->branch_id)
                    ->where('status', 'Available')->where('id', 'LIKE', '%'.$request->name.'%')->groupBy('book_type_id')->get();

    $book_type = $bt->where('book_type.name', 'like', '%'.$request->name.'%');

    $array = [];
    foreach ($book_type as $key => $value){
        $array[] = [
            'id' => $value['id'],
            'text' => $value['book_type']['name']
        ];
    }
    return json_encode(['results' => $array]);
}

这会导致“未找到结果”。但是,当我使用

$book_type = $bt->where('book_type.name', $request->name);

它返回一个数据,所以我相信我的初始查询是正确的并且不是空的,但这不是我想要的,因为我使用它进行搜索,并且我不希望我的用户输入整个单词以将其输出到 select2。

如果我不使用关系,$book_type like 查询会起作用。

【问题讨论】:

    标签: php ajax eloquent jquery-select2


    【解决方案1】:

    您可以使用whereHas 方法过滤关系:

    $book_type = books::with('book_type')
                 ->where('branch_id', $employee->branch_id)
                 ->where('status', 'Available')
                 ->where('id', 'LIKE', '%'.$request->name.'%')
                 ->whereHas('book_type', function($query) use ($request) {
                     $query->where('book_type.name', 'LIKE', '%'.$request->name.'%');
                 }
                 ->groupBy('book_type_id')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-22
      • 2013-07-03
      • 1970-01-01
      • 2021-04-21
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多