简体   繁体   中英

Laravel SQLSTATE[42S22]: Column not found: 1054

Hi I am building a simple search function on Laravel, and I get the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'landmarks' in 'where clause' (SQL: select * from locations where exists (select * from landmarks where locations . id = landmarks . location_id and landmarks LIKE %%))

My search function consist of a textbox in my view and I want to display the results underneath it after clicking on search. However, in my SearchController the following code is found in my index function:

public function index(Request $request){
    $landmarks = $request->input('location');
    //if($landmarks != ''){
      $locations = Location::whereHas('landmark', function($query) use ($landmarks) {
          $query->where('landmarks', 'LIKE', '%' . $landmarks . '%');
      })->get();
    //}

    return view('pages.search', compact('location'));
  }

I suspect it to be the problem that my 'location' input is empty. I am not sure how to handle this.

Use eager loading ->with() instead

$locations = Location::with(['landmark' => function($query) use ($landmarks) {
     $query->where('_the_column_name_on_your_landmarks_table', 'LIKE', '%'
                   . $landmarks . '%');
}])->get();

Try this.

public function index(Request $request){
    $landmarks = $request->input('location');
    //if($landmarks != ''){
      $locations = Location::whereHas('landmarks', function($query) use ($landmarks) {
          $query->where('landmark', 'LIKE', '%' . $landmarks . '%');
      })->get();
    //}

    return view('pages.search', compact('location'));
  }

I assume "landmarks" is your relationships or method name and you have "landmark" as column name.

whereHas method first parameter should be the relationship or method name and then on where method first parameter it should be a column name that exists on the related table landmarks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM