Laravel加入LIKE CONCAT

时间:2018-02-08 11:33:58

标签: php mysql laravel-5 eloquent left-join

Laravel 5.1.11

我在我的商店进行了简单的搜索:

public function search($request $request)
{
        return Catalog::where('title', 'like', '%'.$request->searchQuery.'%')
            ->orderBy('id', 'desc')
            ->paginate(50);
}

这是有效的!

但人们正在寻找商品:Pump BOSCH。搜索结果为空。

因为我更改了我的选择:

public function search($request $request)
{
    $searchQ = preg_split('/\s+/', $request->searchQuery, -1, PREG_SPLIT_NO_EMPTY);
    return Catalog::where(function ($q) use ($searchQ) {
               foreach ($searchQ as $value) {
                   $q->orWhere('title', 'like', "%{$value}%");
               }
           })
           ->orderBy('id', 'desc')
           ->paginate(50);
}

这是有效的,并显示所有Pumps

但我想只展示一个Pump bosch

我的数据库表manufactories

|  id  | title  |
| :--: | :----- |
|   1  |  AlKO  |
|   2  |  BOSCH |

AND catalogs,其中m_id来自表格id manufactory

|  id  |  m_id | title |     url    |
| :--: | :---: | :---- | :--------- |
|   1  |   1   |  pump | pump-alko  |
|   2  |   2   |  pump | pump-bosch |
  

如何更改MySQL搜索查询(添加LEFT JOIN和CONCAT)以查找Pump bosch?   使它看起来像这样:CONCAT('catalogs.title', ' ', 'manufactories.title') LIKE '%'.$request->searchQuery.'%'

2 个答案:

答案 0 :(得分:2)

你可以这样做,

        $data = DB::table('manufactories')
            ->join('catalogs','manufactories.id','=','catalogs.m_id')
            ->select('manufactories.title','catalogs.title')
            ->where(DB::raw('CONCAT(manufactories.title," ",catalogs.title)'), 'like',"%{$value}%")
            ->get();

我希望它有所帮助,

答案 1 :(得分:1)

您可以使用Query Builder进行连接,例如

DB::table('catalogs')
    ->select('catalogs.*')
    ->join('manufactories', 'catalogs.m_id', '=', 'manufactories.id', 'left')
    ->where(function($q) use ($searchQ) {
        foreach ($searchQ as $value) {
            $q->orWhere('manufactories.title', 'like', "%{$value}%");
            $q->orWhere('catalogs.title', 'like', "%{$value}%");
        }
    })
    ->get();