weixin_33704234 2019-03-11 10:12 采纳率: 0%
浏览 70

Laravel Select2搜索

I use the select2 jquery plugin but I can't search for the data that I want to output. I've been trying to search the name of a book in my database which should be available and with the company branch, I am currently in. I'm dealing with 2 tables for this.

books

book_type_id [1, 2]

status ['Available', 'Available']

book_type

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

and

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]);
}

This results in a "no results found". However, when I use

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

It returns a data so I believe my initial query is correct and not empty but this is not what I want because I use this for searching and I don't expect my user to type the whole word to output it to select2.

The $book_type like query works if I don't use relationship.

  • 写回答

1条回答 默认 最新

  • weixin_33725722 2019-03-11 10:23
    关注

    You can use whereHas method to filter through the relations:

    $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();
    
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能