我使用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:选择count(*)作为
city
中的聚合(city
。title
喜欢%fars%或province
。title
喜欢%fars%))
如果我发表评论,orwhere
就可以了。
那你怎么用orwhere
写这个呢?
答案 0 :(得分:2)
而不是:
$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);
答案 1 :(得分: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%");
});