How to apply And where condition in orWhere? - laravel

I want to display data from cv table where user_id is $request->id.
Also, filtering is done so i have to put lots of orWhere.
Because of this my code is not working as expected.
Sorry question is a little bit confusing.
$search = $request->input('search.value');
$results = cv::with(['industrySegments','jobLocations','jobPositions','languages'])->where('user_id',$request->id);
$results->orWhere('name','LIKE',"%{$search}%");
$results->orWhere('gender','LIKE',$search);
$results->orWhere('contact','LIKE',$search);
$results->orWhere('contact2','LIKE',$search);
This code doesn't work.
whenever i type something in search button it displays data that is not supposed to be display.
I want to display only the data whose user_id is $request->id.

i think what you wanted to do is advanced where
your query will be like this
$results = cv::with(['industrySegments','jobLocations','jobPositions','languages'])->where('user_id',$request->id)->where(function($q)use($search){
$q->where('name','LIKE',"%{$search}%")->orWhere(..........;
})->get();
therefore you can play around with where / orWhere

Test next code:
$results = cv::with(['industrySegments','jobLocations','jobPositions','languages']);
if(!empty($request->id))
{
$results->where('user_id',$request->id);
}
else
{
$results->orWhere('name','LIKE',"%{$search}%");
$results->orWhere('gender','LIKE',$search);
$results->orWhere('contact','LIKE',$search);
$results->orWhere('contact2','LIKE',$search);
}

Related

How can I extract the actual values from a database call for subsequent processing?

Apologies for such a vague question title, but I don't know the correct terminology to use for the problem I've got.
I'm developing a search function within which growers enter the name of their crop, the database is probed for the ID for that crop, and a second database call returns factsheets that are associated with that crop ID.
Usually, only one ID will be returned, but for some crops (e.g. asian pear, european pear), two IDs will be returned if the grower enters "pear".
My code returns the requisite ID(s), but I'm having trouble "extracting" the actual ID values from what is being returned (I don't know its name - it looks like objects within an array).
So my code
$cropID = Crop::where('name','like','%'.$search.'%')
->select('id')
->get();
returns, for $search = "pear",
$cropID = [{"id":4},{"id":112}]
I want to get the id values into a structure that I can loop through to search for factsheets associated with each ID, eg.
foreach($obj as $key => $value)
{
... do stuff with $value
}
What do I have to do with $cropID to smooth the way to subsequently get a foreach loop (if that's the correct approach) to work?
Thanks, Tom.
$crops = Crop::where('name','like','%'.$search.'%')
->select('id')
->get();
foreach($crops as $crop) {
echo $crop->id;
// Factsheet::where('crop_id', $crop->id)->get();
}
Or you can pluck it out
$cropIds = $crops->pluck('id');
foreach($cropIds as $id) {
echo $id;
// Factsheet::where('crop_id', $id)->get();
}

Remove Limit From Eloquent Query

How can I remove the limit/offset from the below query?
$query = TestModel::where('a', 'b')->limit(100);
$query->removeLimit();
I'm using a query from another module and I don't want to change the code.
You can reset the $limit property:
$query = TestModel::where('a', 'b')->limit(100);
$query->limit = null;
$unlimited = $query->get();
$query->getQuery()->limit = null;
One can reset the limit by passing the null value to the limit method.
$query->limit(null);
Works both with Eloquent\Builder and Query\Builder.
The simple answer to your question is - you cannot. Because you have already filtered the result set to a limit of 100 tuples.
What is the reason for you to avoid the change in code in the Model? Because what #Dhruv has suggested is the correct way to achieve what you want to.
In fact, if you still want to keep the code intact. You can rather define another function in your model this way and use it internally in your old function:
public function newFunction(){
return TestModel::where('a', 'b')->get();
}
public function oldFunction(){
return $this->newFunction()->limit(100);
}
Keeping your code consistent, then use newFunction() in your Controller to do whatever you want to.
get(): To get all record from table use get():
$query = TestModel::where('a', 'b')->get();
limit(): To limit the number of results returned from the query
$query = TestModel::where('a', 'b')->limit(10)->get();

Laravel 5 PHP - filter results with input value

I have this where I get all my tournaments $tournaments = Tournament::all();. Now I want to let the user filter these on the go in the view... I would like to have an <input> where the user enters a few characters and then the results filter on tournaments that have those characters in the name.
I have found this* online but I dont know how to populate that $keyword. It would be best if the results filter after every character that is entered in the inputfield. If this is not possible, then make this a form that sends this $keyword to Controller and retrieves the new results on the same page!
* $tournament = Tournament::where('name', 'LIKE', '%'.$keyword.'%')->get();
How do I do this? I don't know... Please provide some code in the answer.
Thx
Are you wondering how to get the input of a posted value? You can use the Input::get() method.
$keyword = Input::get('keyword');
if(isset($keyword)){
$tournaments = Tournament::where('name', 'LIKE', "%$keyword%")->get();
}else{
$tournaments = Tournament::all();
}
Also can also use jQuery UI Autocomplete function to progressively search for results.

db active records

I'm trying to get some data from my database with active records,and I'm having the following problem. I wanna learn how to do it with active records since after this code i have a ton of joins and other stuff. Otherwise I would write a normal query.
$this->db->where("sa.country", $country);
// I NEED TO OPEN BRACKETS HERE SO THAT I CAN GET THE LANGUAGES IF THERE IS DATA IN ONE OF THE ARRAYS
if (isset($lid[0]))$this->db->where("sa.lang", $lid[0]);
if (isset($lid[1]))$this->db->or_where("sa.lang", $lid[1]);
if (isset($lid[2]))$this->db->or_where("sa.lang", $lid[2]);
if (isset($lid[3]))$this->db->or_where("sa.lang", $lid[3]);
if (isset($lid[4]))$this->db->or_where("sa.lang", $lid[4]);
//AND CLOSE THEM HERE
My goal is to get a specific country from db, with the corresponding languages that are in the arrays.
I think you should use WHERE...IN...! See help about 'where in'.
With ActiveRecord:
$this->db->where_in("sa.lang",$lid);
Does this help?
$this->db->where("sa.country", $country);
// loop through *set* languages
foreach($lid as $item)
{
$this->db->where('sa.lang', $item);
}
// will return a query object
return $this->db->get('my_table');
Here is how I solved the problem for anyone interested in the solution.
$this->db->where("(`sa`.`lang` = '$lid[0]' OR `sa`.`lang` = '$lid[1]' OR `sa`.`lang` = '$lid[2]' OR `sa`.`lang` = '$lid[3]' OR `sa`.`lang` = '$lid[4]')");

CakePHP Pagination sort() on Related Models

I have two models: Plans and PlanDetails.
Relationship is: PlanDetails hasMany Plans. Plans belongTo PlanDetails.
In the PlanDetails view.ctp, I am pulling in related Plans.
I am trying to sort the Plans by ANY field (I've tried them all), and I cannot get it working. I assume I am overlooking something very simple.
Here is my base code:
PlanDetail >> view.ctp:
...foreach ($planDetail['Plan'] as $plan_edit) :
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}...
<?php echo $this->Paginator->sort('Plan ID', 'Plan.id'); ?>...
...<?php echo $plan_edit['id']; ?>
plan_details_controller.php:
...function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid plan detail', true));
$this->redirect(array('action' => 'index'));
}
$this->PlanDetail->recursive = 2; // To run the editable form deeper.
$this->set('planDetail', $this->PlanDetail->read(null, $id));
$this->set('plan', $this->paginate('Plan'));
}...
I should add, no errors are being thrown and the sort() arrows on the ID field are showing as expected, but the sort order DOES not change when clicked either way.
Sorry, I'm not able to comment on the question itself, but I've noticed that in your action, you set planDetail to be the PlanDetail record you read (with recursive set to 2), and then you set plan to be the result of the paginate call.
Then, in your view template, you're iterating over $planDetail's contained Plan association, like this:
foreach ($planDetail['Plan'] as $plan_edit):
But in order to get the sorting and pagination done, you need to be displaying the results of the paginate call i.e. iterate over the records contained in $plan.
Do a debug($plan) in your view template to see what results you get there and to see if the records' ordering changes when you sort by different fields.
Also, perhaps you're using syntax I'm not aware of, but if you simply call $this->paginate('Plan') in your controller, I don't know that you're going to get only the related Plan records for your particular PlanDetail record. (There's nothing tying the $id passed into your view action with the Plan records.) You might need to add some conditions to the paginate call, like so:
$this->paginate['Plan'] = array('conditions' => array('Plan.plan_detail_id' => $id));
$this->set('plans', $this->paginate('Plan'));
Here is what I did to solve this. Based on some helpful direction from johnp & tokes.
plan_details/view.ctp:
...$i = 0;
foreach ($plan as $plan_edit) : // note $plan here.
}...
In my plan_details_controller.php view action:
$conditions = array("Plan.plan_detail_id" => "$id");
$this->set('plan', $this->paginate('Plan', $conditions)); // note "plan" in the first argument of set (this is required to pass the results back to the view). Also. The $condition is set to return ONLY plans that match the plan_detail_id of id (on the plan_details table).
And in my view, in order to get my results (because I changed the array name), I had to change the way I was getting the values to:
$plan_edit['Plan']['modified'] // note I placed ['Plan'] in front of these calls as the array called for this to get the data...
Well until the next problem! SOLVED.

Resources