Reputation: 724
I am using eloquent as ORM and I want to use where
in multi-table like this:
$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();
However, I encounter the following error:
Message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'province.title' in 'where clause' (SQL: select count(*) as aggregate from
city
where (city
.title
like %fars% orprovince
.title
like %fars%))
If I comment the orwhere
it works.
So how can you write this with orwhere
?
Upvotes: 4
Views: 762
Reputation: 111899
Instead of:
$raw_query = $raw_query->where(function ( $q ) use ( $search_data ) {
$q->where('city.title' , 'like' , "%$search_data%")
->orwhere('province.title' , 'like' , "%$search_data%");
});
}
you should use:
$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%");
});
});
Notice that the where .. orWhereHas was wrapped here in additional where
and this gives you confidence you can add any other conditions as for example selecting only active cities:
$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);
Upvotes: 3
Reputation: 2604
Try to use 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%");
});
Upvotes: 1