我使用eloquent作为ORM,我想在多表中使用where
,如下所示:
$raw_query = EntityCity::with(['province']);
$raw_query = $raw_query->where(function ( $q ) use ( $search_data ) {
$q->where('city.title' , 'like' , "%$search_data%")
->orwhere('province.title' , 'like' , "%$search_data%");
});
}
$this->data[ 'result_list' ] = $raw_query->limit($this->per_page)
->orderByDesc("time_insert")
->offset(( $page_num - 1 ) * $this->per_page)
->get();
但是,我遇到以下错误:
消息:SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'province.title'(SQL:从
city
中选择count(*)作为聚合(city
.title
喜欢%fars%或province
.title
like %尔斯%))
如果我评论orwhere
它的工作原理。
那你怎么用orwhere
写这个呢?
代替:
$raw_query = $raw_query->where(function ( $q ) use ( $search_data ) {
$q->where('city.title' , 'like' , "%$search_data%")
->orwhere('province.title' , 'like' , "%$search_data%");
});
}
你应该使用:
$raw_query = $raw_query->where(function($q) {
$q->where('city.title', 'like', "%$search_data%")
->orWhereHas('province', function ( $q ) use ( $search_data ) {
$q->where('province.title' , 'like' , "%$search_data%");
});
});
请注意,where ..或WhereHas被包装在其他where
中,这使您有信心可以添加任何其他条件,例如仅选择活动城市:
$raw_query = $raw_query->where(function($q) {
$q->where('city.title', 'like', "%$search_data%")
->orWhereHas('province', function ( $q ) use ( $search_data ) {
$q->where('province.title' , 'like' , "%$search_data%");
});
})->where('active', 1);
尝试使用orWhereHas
:
$raw_query = $raw_query->where('city.title', 'like', "%$search_data%")
->orWhereHas('province', function ( $q ) use ( $search_data ) {
$q->where('province.title' , 'like' , "%$search_data%");
});