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% or province.title like %fars%))
If I comment the orwhere it works.
So how can you write this with orwhere?
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);
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%");
});
Related
i have 3 query filter that will be used to search. The first query is selected option query, the second query is date query when i want to search betwen date start and date end query. the last query is about searching name, etc. The only working query just the last one. What happens with my code, i thought there doesn't any problem with my code
Here is my code that using filter
filtercontroller.php
public function viewType(Request $request, ReportViewAll $reportview){
$reportview = $reportview->newQuery();
if ($request->has('program')) {
if($request->input('program') == 'reportall'){
$reportview;
}
elseif($request->input('program') == 'reportactive'){
$reportview->where('crewprogram_isdisabled', '=',0);
}
elseif($request->input('program') == 'reporthistory'){
$reportview->where('crewprogram_isdisabled', '=',1);
}
}
if(($request->has('datestart') && $request->has('dateend'))){
$reportview->whereBetween('crewprogrammemo_placement_date',
array($request->input('datestart'), $request->input('dateend')));
}
if($request->has('search')){
$reportview->where ( 'employee_nik', 'LIKE', "%{$request->search}%" )
->orWhere ( 'employee_nama', 'LIKE', "%{$request->search}%" )
->orWhere ( 'show_focus_id', 'LIKE', "%{$request->search}%" )
->orWhere ( 'show_name', 'LIKE', "%{$request->search}%" );
}
return $reportview->get();
// return view('CrewProgram.ReportView.index', compact('reportview'));
}
What should i do for the three of them to start working, not just 1 query that's working
Edited
public function viewType(Request $request, ReportViewAll $reportviewall){
$reportviewall = $reportviewall->newQuery();
if ($request->has('program')) {
if($request->input('program') == 'reportall'){
$reportviewall;
}
elseif($request->input('program') == 'reportactive'){
$reportviewall->where('crewprogram_isdisabled', '=',0);
}
elseif($request->input('program') == 'reporthistory'){
$reportviewall->where('crewprogram_isdisabled', '=',1);
}
}
if(($request->has('datestart') && $request->has('dateend'))){
$reportviewall->whereBetween('crewprogrammemo_placement_date',
array($request->input('datestart'), $request->input('dateend')));
}
If($request->has('search')){
$reportviewall->where(function($query) use($request) {
$query->where('employee_nik', 'LIKE', "%{$request->search}%" )
->orWhere ( 'employee_nama', 'LIKE', "%{$request->search}%" )
->orWhere ( 'show_focus_id', 'LIKE', "%{$request->search}%" )
->orWhere ( 'show_name', 'LIKE', "%{$request->search}%" );
});
}
$reportviewall = $reportviewall->get();
return view('CrewProgram.ReportView.index', compact('reportviewall'));
}
You have two options:
OR
using orWhere() :
Model::query()->where([])->orWhere([])->get();
AND using 2nd array :
Model::query()->where([['column1' , '!=' , 'value1'] , ['column2' , '=' , 'value2'] , ['column3' , '<' , 'value3']])->get();
The problem with your queries is that when you pass a search filter, you are chaining multiple orWhere()'s to the query, which means that any query to one of these filters that is true will be returned, it won't matter if any of the other filters were false, the solution to this is to wrap the search filter in a callback function, like this:
if($request->has('search')){
$reportview->where(function($query) use($request) {
$query->where('employee_nik', 'LIKE', "%{$request->search}%" )
->orWhere ( 'employee_nama', 'LIKE', "%{$request->search}%" )
->orWhere ( 'show_focus_id', 'LIKE', "%{$request->search}%" )
->orWhere ( 'show_name', 'LIKE', "%{$request->search}%" );
});
}
Whats the best way to build an Product Search Filter with an <select>?
My Route:
Route::any ( '/search', function () {
$q = Input::get ( 'q' );
if($q != ""){
$products = Product::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'description', 'LIKE', '%' . $q . '%' )->paginate (200)->setPath ( '' );
$pagination = $products->appends ( array (
'q' => Input::get ( 'q' )
) );
if (count ( $products ) > 0)
return view ( 'search' )->withDetails ( $products )->withQuery ( $q );
}
return view ( 'search' )->withMessage ( 'No Products!' );
} );
Now i want add an Drop down Filter with <select> to Search Page like:
<select name="sortby">
<option value="newproducts">New Products</option>
<option value="cheapprice">Cheapest Price</option>
</select>
Can i do it in my Route like:
if (select( ..newproducts... ) > 0)
return view ( 'search' )->withDetails ( $products )->withQuery ( $q );
}
Thanks for some tips:)
Sure you can add it there, but not with a conditional. You already pass a query parameter to search, just give the select a name and send that along too. You would use ->orderBy(...) on you collection you get when searching for $q.
// from your html
<select name="sortby">
// in your controller/route
$products->orderBy(request->get('sortBy'))
// new products
If (request->get('sortBy') === 'newproducts')
$products->orderBy('created_at', 'desc');
// cheap price
If (request->get('sortBy') === 'cheapprice')
$products->orderBy('price', 'asc');
https://laravel.com/docs/5.5/eloquent-collections#available-methods
I want sort my Search Results with an URL. I cant use Controller in my way because i use Route for /search.
My Search Route:
Route::get ( '/', function () {
$mydb= Product::paginate(200);
return view ( 'search' )->withProduct($mydb);
} );
Route::any ( '/search', function () {
$q = Input::get ( 'q' );
$sort = Product::where ( 'name', 'LIKE', '%' . $q . '%' )->orderBy('created_at','desc')->paginate(20);
if($q != ""){
$products = Product::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'description', 'LIKE', '%' . $q . '%' )->paginate (200)->setPath ( '' );
$pagination = $products->appends ( array (
'q' => Input::get ( 'q' )
) );
if (count ( $products ) > 0)
return view ( 'search' )->withDetails ( $products )->withQuery ( $q );
}
Now i want create an Button where i can Sort the results from query search.
Button Example:
Sort by Price
I want add like this to my Route:
$sort = Product::where ( 'name', 'LIKE', '%' . $q . '%' )->orderBy('created_at','desc')->paginate(20);
This dont work..
And then add the {{ $sort }}behind my Button URL like:
Sort by Price
Any Idea how i can do it correct? Sorry i am an Beginner with Laravel and i know its not correct.
Thanks!
There appears to be a lot of errors in your code.
But this line
Sort by Price
could be
Sort by Price
Then in your closure
$q = Input::get ( 'q' );
$orderby = Input::has('orderby') ? Input::get('orderby') : 'created_at';
$sort = Product::where ( 'name', 'LIKE', '%' . $q . '%' )->orderBy($orderby,'desc')->paginate(20);
I am not able to create this sql query on laravel:
select * from `events_theatre` where
event_id IN (
select id from events where (`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` ='theatre') and `events`.`deleted_at` is null
)
or event_id IN (
select id from events inner join events_managers on events.id = events_managers.event_id and events_managers.user_id = 1
)
and `events_theatre`.`deleted_at` is null
The Events_Theatre model has this relationship:
public function event()
{
return $this->hasOne('App\MyEvent', 'id');
}
While the MyEvent model has this relationship:
public function managers()
{
return $this->belongsToMany('App\User', 'events_managers', 'event_id', 'user_id');
}
Pratically an Events_Theatre model is an Event model, and an Event model may have many managers but just 1 admin.
I need to get that Events_Theatre (and their MyEvent) whose user is an admin or one of the managers.
I tried with this eloquent query:
$list = App\Events_Theatre::whereIn('event_id', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre'])
->orWhereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
});
But I get this sql query:
select * from `events_theatre` where
exists (
select * from `events` where (
`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` = 'theatre'
) or exists (
select * from `users` inner join `events_managers` on `users`.`id` = `events_managers`.`user_id` where `events_managers`.`event_id` = `events`.`id` and `user_id` = 1
)
and `events`.`deleted_at` is null
) and `events_theatre`.`deleted_at` is null
But its wrong. How can I solve this?
Thanks
UPDATED
I got the answer. This is the eloquent code I used:
$list = Events_Theatre::whereHas('event', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre']);
})->orWhereHas('event', function ($query) {
$query
->whereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
})->get();
You can try has method
App\Events_Theatre::has('event')->orhas('managers')->get();
What im trying is to get my AppNamespace, AppModule and AppController. So i use Laravel 5.2 with eloquent and run:
$this->namespaceModel->whereTitle( $this->namespace )
->whereHas( 'modules', function ( $q )
{
$q->whereTitle( $this->module );
} )
->whereHas( 'modules.controllers', function ( $q )
{
$q->whereTitle( $this->controller );
} )
->first();
This gives me a false or true depending on the results, but not the record itself. I've used a with() too but that doesnt return a record IF the whereHas() returns true. How can i fix that?
Alternatively you can use joins on that query like this:
$this->namespaceModel->whereTitle( $this->namespace )
->join( 'modules', 'namespaces.id', '=', 'modules.namespace_id')
->join( 'controllers', 'modules.id', '=', 'controllers.module_id')
->where( 'modules.title', $this->module )
->where( 'controllers.title', $this->controller )
->select('namespaces.*')
->with('modules', 'modules.controllers')
->first();