简体   繁体   中英

Laravel 5 nested search query

I'm trying to make a nested search query but I get this error. I'm trying to search for a company name joined by a company_id.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'company.name' in 'where clause' (SQL: select count(*) as aggregate from `position` where `to_date` >= 2016-06-16 and `company_id` = 123795854693734 and `title` like %searchquery% and `company`.`name` like %searchquery% and `location` like %%)

Here is my controller function

public function Search(){

    $keyword = Input::get('q');
    $location = Input::get('l');

    $data = Position::where('to_date', '>=', date('Y-m-d'))
    ->where('company_id', '=', $company_id)
    ->where('title', 'like', '%'.$keyword.'%')
    ->where('company.name', 'like', '%'.$keyword.'%')
    ->where('location', 'like', '%'.$location.'%')
    ->orderBy('from_date', 'desc')
    ->paginate(10);

    $data = array(
        'data' => $data,
    );

    return view('myview', $data);

}

The model works perfectly. But here it is anyway.

namespace App;
use Illuminate\Database\Eloquent\Model;

class Position extends Model {
    protected $table = 'position';
    protected $guarded = array("id");
    protected $hidden = array();
    protected $appends = array('local_ad');

    protected $fillable = ['title', 'company_id', 'location'];

    public function company() {
        return $this->belongsTo('App\Company', 'company_id', 'id');
    }

}

This function should be

public function Search(){

    $keyword = Input::get('q');
    $location = Input::get('l');

    $data = Position::where('to_date', '>=', date('Y-m-d'))
    ->where('company_id', '=', $company_id)
    ->where('title', 'like', '%'.$keyword.'%')
    ->with(['company' => function( $q ) use ($keyword) {
        ->where('name', 'like', '%'.$keyword.'%')
    }])
    ->where('location', 'like', '%'.$location.'%')
    ->orderBy('from_date', 'desc')
    ->paginate(10);

    $data = array(
        'data' => $data,
    );

    return view('myview', $data);
}

but this does not do a join, this will fetch position, there is a whereHas in Eloquent, you should explore that also.

You are not using your relation or joining to the company table actually, that's why it can't find it.

Simply, you can use whereHas method to filter positions with company names.

$data = Position::whereHas('company', function ($q) use ($keyword) {
    $q->where('name', 'like', '%'.$keyword.'%');
})->where('to_date', '>=', date('Y-m-d'))
  ->where('company_id', '=', $company_id)
  ->where('title', 'like', '%'.$keyword.'%')
  ->where('location', 'like', '%'.$location.'%')
  ->orderBy('from_date', 'desc')
  ->paginate(10);

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