Laravel Select2搜索

问题描述 投票:0回答:1

我使用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就像查询一样。

php ajax eloquent jquery-select2
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.