Laravel 选择 2 搜索

Laravel Select2 Search

我使用了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]);
}

这导致 "no results found"。但是,当我使用

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

它 returns 一个数据,所以我相信我的初始查询是正确的而不是空的,但这不是我想要的,因为我用它来搜索,我不希望我的用户输入整个单词将其输出到 select2.

如果我不使用关系,$book_type 类查询就可以工作。

您可以使用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();