I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:
$where = [['Participants.Client_Id','IN', $clientId]];
DB::table('Participants')->where($where)->get()
Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw
DB::table('participants)->whereIn('Participants.Client_Id',$clientId)->get();
You must collect the IDs in the $clientId variables.
If I understand, you could do something like that :
$wheres = [['Participants.Client_Id','IN', [$clientId]]];
$query = DB::table('Participants');
foreach($wheres as $where) {
$query->where($where[0], $where[1], $where[2]);
}
$participants = $query->get();
As laravel document , you can use array in where and each element of this array must be a array with three value . So your $where variable is correct.
But as I searched in operator is not supported by query builder of where.
Related
I have problem with my laravel query.
Now I use query like this:
$courses = Course::whereJsonContains('schedule->day', 1)->get();
It doesn't work.
I'm using postgreSql 9.6 and my database and raw query look like this
http://sqlfiddle.com/#!17/88fd2/1/0
I want to select class where have schedule in day = 1
If you define the column as schedule->day, MySQL assumes that this is an array of integers. In your case it's an array of objects, so you have to target the parent array and add the property name you are looking for in the second argument.
Like so:
$courses = Course::whereJsonContains('schedule', ['day' => 1])->get();
I solved with
$courses = Course::whereJsonContains('schedule', [['day' => '1']])->get();
I solved with
$products=ProductShop::active()
->whereJsonContains('tag', [['value' => "tampa"]])->get();
If you're querying the value уоu don't need to use whereJsonContains, simply use a regular where query such as:
$courses = Course::where('schedule->day', 1)->get();`
If you want to check if day exists in Json, use whereJsonLength such as:
$courses = Course::whereJsonLength('schedule->day', '>', 0)->get();
When building a query to find multiple values from a model, eloquent would look something like this:
return Contact::whereIn('user_name', explode(',', $userNames)
But let's say that the value for userNames is ['foo', 'bar']; but I only have foo as a valid username, is there a way to get bar (all failed to find) out as part of the same query without having to compare the result ->get() against the request?
It's not possible to get the query to return the list of username that doesn't exist from the given condition. But you could do this.
$allUserNames = explode(',', $userNames);
$validUserNames = Contact::whereIn('user_name', $allUserNames)
->pluck('user_name')
->toArray();
$invalidUserNames = array_values(array_diff($allUserNames, $validUserNames));
You can use array diff to remove the unvalid value form the select region, and you lost the ->get() to get the results;
return Contact::whereIn('user_name', array_diff(explode(',', $userNames, ['bar']))->get()
So, basically I have a field in a table from my database which contains some values separated by comma (something like: value1, value2, value3). I need to check somehow if one or more of these values are contained in an array of values and retrieve the model(s). I'd like a solution using Eloquent Model Query to achieve this, if not possible with Model Query, then a Query Builder solution will be okay as well, or maybe something alternative.
Tried to use a function inside the where statement where I loop the array of values and just query the model using like operator to check if field value matches the values from the array and in the end I got something like this:
$devices = explode(",", Input::get("devices"));
$products = Product::where(function ($q) use ($devices) {
foreach ($devices as $device) {
$q->orWhere("compatible_devices", "like", "%" . $device . "%");
}
})->get();
Works quite well so far.
I'm having issues with an array returned from DB::select(). I'm heavily using skip and take on Collections of eloquent models in my API. Unfortunately, DB::select returns an array, which obviously doesn't work with skip and take's. How would one convert arrays to a collection that can utilise these methods?
I've tried
\Illuminate\Support\Collection::make(DB::select(...));
Which doesn't quite work as I expected, as it wraps the entire array in a Collection, not the individual results.
Is it possible to convert the return from a DB::select to a 'proper' Collection that can use skip and take methods?
Update
I've also tried:
$query = \Illuminate\Support\Collection::make(DB::table('survey_responses')->join('people', 'people.id',
'=', 'survey_responses.recipient_id')->select('survey_responses.id', 'survey_responses.response',
'survey_responses.score', 'people.name', 'people.email')->get());
Which still tells me:
FatalErrorException in QueryHelper.php line 36:
Call to a member function skip() on array
Cheers
I would try:
$queryResult = DB::table('...')->get();
$collection = collect($queryResult);
If the query result is an array, the collection is filled up with your results. See the official documentation for the collection. Laravel5 Collections
For anyone else that's having this sort of problem in Laravel, I figured out a work around with the following solution:
$query = DB::table('survey_responses')->join('people', 'people.id', '=', 'survey_responses.recipient_id')
->select('survey_responses.id', 'survey_responses.response', 'survey_responses.score', 'people.name', 'people.email');
if(isset($tags)){
foreach($tags as $tag){
$query->orWhere('survey_responses.response', 'like', '%'.$tag.'%');
}
};
// We apply the pagination headers on the complete result set - before any limiting
$headers = \HeaderHelper::generatePaginationHeader($page, $query, 'response', $limit, $tags);
// Now limit and create 'pages' based on passed params
$query->offset(
(isset($page) ? $page - 1 * (isset($limit) ? $limit : env('RESULTS_PER_PAGE', 30)) : 1)
)
->take(
(isset($limit) ? $limit : env('RESULTS_PER_PAGE', 30))
);
Basically, I wasn't aware that you could run the queries almost incrementally, which enabled me to generate pagination chunks before limiting the data returned.
I have the problems using the array input as a value in WHERE clause.
But don't want to use more than once in WHERE clause code.
In my case, this is what I want :
$cond = array('job_id' => $job_id_var, 'job_name' => $job_name_var);
//WHERE clause
$this->where($cond); //only using once WHERE clause code like this, array as input
//which means
WHERE job_id = '$job_id_var' AND job_name = '$job_name_var'
is it possible to do that in codeigniter?
Yes, the ->where() method can support that.
Since you do not want to cascade it:
$this->db->where('job_id', $job_id_var);
$this->db->where('job_name', $job_name_var);
->where() can handle array input as well:
$cond = array('job_id'=>$job_id_var, 'job_name'=>$job_name_var);
$this->db->where($cond); // here, only used once.
$query = $this->db->get('hello_table');
$result = $query->result_array();
return $result;