Laravel Multiple wherein's - php

How can I do multiple wherein in laravel?
$devices = DB::table('foo')
->select('foo.*')
->whereIn('bar1', $request->bar1)
->whereIn('bar2', $request->bar2)
->get();
Above is my sample code but it is returning me an empty array.

It is ok to use multiple WHERE IN constraints in your query. The code you provided is also ok.
If you're getting no results, make sure that values of $request->bar1 and $request->bar2 are what you expect - they should be arrays of values that contain what you want your bar1/bar2 columns to be.
You can always get the generated SQL by calling toSql() instead of get(), you can also inspect the values of parameters by calling getBindings().

Related

jenssegers/laravel-mongodb's where() and raw() produces different result for same query

I am using jessengers/laravel-mongodb in one of my project. I would like to use raw mongodb query rather than the other functions in jessengers library. when i write a simple query using raw() to get two field values from database, it returns the complete document. So i tried with where() function, the cursor shows the requested fields only.
I am afraid why the same query shows two different results...
Here is the query with where() function:
$articleDataArray = Article::where('art_xml_data.article.article_id', '=', $articleId)
->get(['art_status', 'art_file_path']);
This query returns a cursor having art_status and art_file_path values only. (As per Neil Lunn's advice I have edited the question to include the result here.)
Result:
But the below query when written in raw() returns the complete fields in the matched document.
$articleDataArray = Article::raw()->find(
array ('art_xml_data.article.article_id' => $articleId),
array ('art_status' => 1, 'art_file_path' => 1)
)->toArray();
Result:

Laravel convert resultset to array

Database table SITE has many columns. One of them is site_id. I need all the site_ids as an array since it has to be fed to a method which accepts only a string array.
What I tried so far is:
$sites = DB::select('select site_id from site_tab');
$sites_arr = $sites->toArray();
But this doesn't produce the result I want. I need $sites_arr to be like ['A','B','C',...]
Please suggest a way to get this done. A solution based on Eloquent is also OK for me.
Thanks
Try this:
DB::table('site_tab')->pluck('site_id')->toArray();
reference pluck
referen toArray
If you open a manual, you will see that
The select method will always return an array of results
So, there's no need to use ->toArray(), as result is already an array.
To get values as array of names you can do:
$site_ids = DB::table('site_tab')->pluck('site_id');
Using ->toArray() here is optional, as you can iterate over $site_ids (which is a Collection) with a foreach too.

Find inside comma separated values field Laravel 5.1

I Need to check if a variable is present inside a comma separated string in mysql field using querybuilder.
I do this
<?php
$parents = DB::table('categorie')>whereRaw('FIND_IN_SET("$categoria->id", parent)')->get();
but didn't return any value.
You should never put variables in the query yourself. Use bindings instead, this will make sure your parameters are correctly escaped.
<?php
$parents = DB::table('categorie')->whereRaw('FIND_IN_SET(?, parent)', [$categoria->id])->get();
You may debug the query using toSql() method after your query, which becomes
DB::table('categorie')->whereRaw('FIND_IN_SET("$categoria->id", parent)')->toSql();
This will clear it out if $categoria->id is being put in the query or not.
I can't comment yet, hence posting it as an answer.

Laravel get single column result as string

Hello I would like to know is it possible to get column value as string. Instead of array in array:
Current query: Number::limit('1000')->get(['number'])->toArray()
The result at the moment is this:
Preferable result:
Before your toArray() call, add pluck('number'):
$result = Number::limit('1000')->get(['number'])->pluck('number')->toArray();
That's it! This will pluck just the number attributes from your result collection, and give you a single-level array.
The reason this works, is because you are getting a Collection back from get():
All multi-result sets returned by Eloquent are an instance of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship.
And the pluck method:
https://laravel.com/docs/5.1/collections#method-pluck
Update
Another, even more succinct method provided by #wunch in the comments:
$result = Number::limit('1000')->lists('number')->toArray();

how to get the where clause in string format using CakePHP3 ORM?

In CakePHP3, there is a ORM that helps with building queries.
From the documentation, I can see that
$query = $articles->find(); // build a query that has not run yet
$query->where(['id' => 1]); // Return the same query object
So in this case, I want the string
WHERE `articles`.`id` = 1
After much googling, I found out that there is a way to return just the where clause of a query object.
$query->where(['id' => 1])->clause('where'); // Return the where clause in the form of a QueryExpression
More googling leads me to find out how to get the QueryExpression to spit out string representation
$query->where(['id' => 1])->clause('where')->sql($valueBinder); // Return the where clause in string format
Here is my problem. I don't know what the $valueBinder is supposed to look like. I don't know how to initialize it.
I am also happy not to use ValueBinder as long as I can get the where clause in string format using CakePHP 3 ORM and in the right SQL dialect. Please assume I am using MySQL.
Please advise.
EDIT
I tried to use $query->valueBinder() as the $valueBinder.
It is empty and does not contain the associated c:0 to the value 1.
To directly answer your question, you can get the SQL for any clause this way:
$binder = new \Cake\ORM\ValueBinder();
$query->clause('where')->sql($binder);
That will return the SQL with the correct placeholders, not with the values to be used. The values live in the $binder variable and are used for statement objects.
As I can see, you only wanted to preserve the internal structure of the where clause to pass it to another query in a different request. Your solution is fine, but I'd like to add that you can also encode a full conditions tree from an existing query:
$where = serialize($query->clause('where'));
$anotherQuery->where(unserialize($where)); // A query in another request
In any case, you need to be careful with what you are unserializing as taking it directly from user input will certainly lead to security problems.
You can choose to omit this param if you like. Please see http://api.cakephp.org/3.0/class-Cake.Database.Query.html#_sql
In addition, you can use the Query member function traverse($visitor, $parts) to isolate the where clause. $visitor is a function that takes a value and a clause. You define the behavior of $visitor. $parts is an array of clause names. I suggest passing array('where') into this param.
My workaround is that I store the conditions in json string format.
Using the same example, what I do is
$data['conditions'] = json_encode(['Articles.id' => 1]); // encode into JSON string
$this->DynamicRules->patchEntity($dynamicRule, $data); // use in edit action of DynamicRulesController
then when I need to reuse the conditions, I do:
$articlesTable = TableRegistry::get('Articles');
$query = $articlesTable->find(); // new query for Articles
$rule = json_decode($dynamicRule->conditions, true); // get back the conditions in associative array format
$query->where($rule); // re-assign the conditions back
This got me what I ultimately wanted.

Categories