使用连接方法进行Laravel搜索

问题描述 投票:-1回答:2

我尝试在我的应用程序中同时搜索帖子标题和帖子标签,所以我在我的搜索功能中使用了连接方法。

这是我的表格:

<div class="search">
      <form class="form-inline" action="/search" method="GET" role="search">
        {{ csrf_field() }}
        <i class="fa fa-search"></i>
        <div class="field-toggle">
          <input type="text" name="search" class="search-form" autocomplete="off" placeholder="Search...">
        </div>
        <button type="submit" name="button">search</button>
      </form>
    </div>

这是我的功能:

public function search() {

  $search = request('search');

  $foods = Food::join('food_ingredient', 'food_ingredient.food_id','=', 'food.id')
         ->join('ingredients','ingredient.id','=','food_ingredient.ingredient.id')
         ->where('food.title', 'LIKE', '%' . $search . '%')
         ->orWhere('ingredient.title', 'LIKE', '%' . $search . '%') //The fix
         ->orderBy('food.created_at', 'desc')
         ->groupBy('food.id')
         ->with('ingredients')
         ->paginate(8);

  return view('front.search', compact('foods'));
}

有了这个,我得到这个错误:

SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'food.title'(SQL:选择count(*)作为来自foods内部连接的聚合food_ingredient food_ingredient.food_id = food.id内部连接ingredients on ingredient .id = food_ingredient.ingredient.id其中food.title LIKE%papper%或ingredient.title LIKE%papper%group by food.id

这是我的数据库:

食品 - >商店帖子

成分 - >储存成分

食品配料 - >商店帖子标签

12

我该如何解决?

PS:我的帖子名称是food,我的标签名称是ingredient(只是命名不同)。

谢谢。

php mysql laravel join
2个回答
0
投票

使用连接时,您需要在where子句中指定表名,因为在joins之后您将有多个列,因此在询问title时需要指定表名:

  $foods = Food::join('food_ingredient', 'food_ingredient.food_id','=', 'food.id')
         ->join('ingredients','ingredient.id','=','food_ingredient.ingredient.id')
         ->where('ingredient.title', 'LIKE', '%' . $search . '%') ...

假设您要搜索成分标题


0
投票

你必须用逗号封装外卡,以便搜索它会是什么样的参数

public function searchOrders($param)
{
    $id = "id";
    $search='%'.$param.'%';

    $orders = DB::select('SELECT o.*,s.name,b.name FROM orders o JOIN users b on o.buyer_id= b.id JOIN users s on o.seller_id=s.id where o.id LIKE  ?', [$search]);

    $data = array(
        "orders" => $orders
    );
    return View('admin.orders.service_search_orders', $data);
}
© www.soinside.com 2019 - 2024. All rights reserved.