我试图做一个嵌套的搜索查询,但是我得到了这个错误。我正在寻找一个由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 %%)这是我的控制器功能
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);
}模型工作得很好。但无论如何,它就在这里。
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');
}
}发布于 2016-06-16 08:44:26
你没有使用你的关系或者加入公司表,这就是为什么它找不到它的原因。
简单地说,您可以使用whereHas方法过滤带有公司名称的职位。
$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);发布于 2016-06-16 08:42:40
这个功能应该是
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);
}但是这不做一个连接,这将获取位置,有一个whereHas在雄辩,你应该探索也。
https://stackoverflow.com/questions/37853963
复制相似问题