In my application i have product table with 4 different types of filters first step is user selects some filter from frontend then via ajax i push them into session and create a array of each type of filters..below is the code i wrote but it not working as i expected it only return results if there are no empty array passed in where clause but i want to fetch results whatever filter we pass in query
filters array
$industrytags = ['Agriculture & Farming','Medical'];
$styletags = ['Modern','Floral'];
$orientationtags = [];
$colortags = ['red','green'];
Query
$updatedproducts = Product::whereIn('industry', $industrytags)->whereIn('style', $styletags)->whereIn('orientation', $orientationtags)->whereIn('color', $colortags)->get();
its not returning any results because now one of filter type is null but i want a query which fetches data with available filter
Try this -
$condition = "orientation IN ('value1', 'value2', 'value3') OR orientation IS NULL";
$updatedproducts = Product::whereIn('industry', $industrytags)
->whereIn('style', $styletags)
->whereRaw($condition)
->whereIn('color', $colortags)->get();
Hope this will help you.
Related
I've done a vanilla install of Solr and Solarium for PHP
Solarium 5.x
PHP 7.1
Solr 8.5.1
I can create and query documents. But all fields I create are returned as arrays - except for "id". obviously there is some schema somewhere that specifies that id is a single-value field. how can I create my own single-value fields? All fields I create are multi-value arrays.
The multi-value field feature is useful but there are only a few cases where I will need it.
It seems I should be able to define the field types and specify whether they are multi-value or not but instead all fields I create are multi-value arrays and I can't appear to change that. the solarium documentation has a section on multi-value fields but not single-value fields.
https://solarium.readthedocs.io/en/stable/documents/#multivalue-fields
I don't see any documentation in solarium for defining the documents and their field types. possibly something is wrong with my installation.
here is my code example:
$client = new Solarium\Client($config);
// get an update query instance
$update = $client->createUpdate();
// create a new document for the data
$doc1 = $update->createDocument();
// add data to the document
$doc1->id = 123; // single value by default
$doc1->name = 'document name'; // always results in an array
$doc1->price = 5; // always results in an array
// add the documents and a commit command to the update query
$update->addDocuments(array($doc1));
$update->addCommit();
// this executes the query and returns the result
$result = $client->update($update);
// then query the documents
$query = $client->createSelect();
$query->setQuery('*:*');
$resultSet = $client->select($query);
echo 'NumFound: '.$resultSet->getNumFound().'<br>';
foreach ($resultSet as $document) {
foreach ($document as $field => $value) {
// I can test to see if $value is an array but my point is that I don't want
// to do so for every single field. how can I define fields that are single-value by default?
echo '<div'> . $field . ' : ' . $value . '</div>';
}
}
this outputs:
NumFound: 1
id : 123
name : Array
price : Array
yes I know how to get those values out of the array but I know there must be some way to get single-value fields by default.
Thanks in advance.
I have discovered that I can define multiValued="false", and many other detailed properties of a field, by manually editing managed-schema (schema.xml) in the conf directory for the core.
however it says at the top of this file:
So now the real question is, how do you edit the SOLR schema?
I'm trying to build my own dynamic filtering for my Angular App and Laravel 5.1 API using $httpParamSerializer(params); and Laravel whereIns.
My goal is to pass a set of fields and values I want to filter on and drill down the records I need.
I loop through the fields in Laravel and perform whereIns, then group them into an array, removing duplicates. Unfortunately, this acts more as an OR than an AND, as each whereIn does a new search to match.
Frontend Query:
var filters = {
'review[]' : ['no', 'yes'],
'user_id[]' : [1]
};
HTTP URL: "http://dde-api.localhost/1.0/userquestions?review%5B%5D=no&review%5B%5D=yes&user_id%5B%5D=1"
DB:
Laravel:
$results = [];
// Loop through each field (`review`, `users`, etc..), then search thru array of params
foreach ($input as $filter_field => $filters_array) {
if ($this->validField($table, $filter_field)) {
$res = DB::table($table)->whereIn($filter_field, $filters_array)->get();
if (!in_array($res, $results)) {
array_push($results, $res);
}
I need the query to work as a multiple WHERE clause (AND, not OR) which loops through and appends where clauses to each field ($filter_field), then searches for matching field values.
So the result should be all yes and no records for user 1. Since user 1 doesn't have a record with review: yes, it uses the record from user_id: 4. This is bad.
How can I append multiple WHERE statements to one query as I loop through multiple fields?
Use Your loop like this
$dbTbOBJ = \DB::table("table_name")
// Loop through each field (`review`, `users`, etc..), then search thru array of params
foreach ($input as $filter_field => $filters_array) {
$dbTbOBJ->whereIn($filter_field, $filters_array);
}
$results = $dbTbOBJ->get()
I have a symfony problem: The functionally works good, but this does not work the way I want.
$res = array("4","2","1","3"); // LIST ID (a.id)
$paginas = new sfDoctrinePager('TbArticle', 2);
$paginas->setQuery(Doctrine::getTable('TbArticle')->createQuery('a')->where('a.ifactive = 1')->andWhere('a.dirimage=1')->andWhere('a.stock<>0')->whereIn("a.id", $res));
$paginas->setPage($page);
$paginas->init();
It works okay, but when I call getResults(), the array order is incorrect. For instance, this sort returns: 1,2,3,4. And I like to get: 4, 2, 1, 3 ($res)
Can you help me?
Unfortubately this cannot be done with the query.
The MySQL queries can be returned ordered using the ORDER BY clause in ascending or descending order. Elements in your array use none. When you pass the array as a parameter for the WHERE IN clause MySQL doesn't care about the order of the elements as you can see.
Fortunately there is a solution :)
First you will have to use Doctrine's ability to create a table of results indexed with what you want. Use this:
Doctrine::getTable('TbArticle')->createQuery('a INDEX BY id')->...;
This will return an array of results where the array keys are the id's of the rows. Then you can rearange the results array to match your $res (assuming that $rows has the rows returned by Doctrine):
foreach ($res as $i) {
$new_array[] = $rows[$i];
}
The tricky part is to make it work with the paginator. But I'm sure you can do that as well (try to retrieve the results from the paginator and rearange them before displaying).
I would like to insert an array into a MYSQL database, preferably using Yii's active record.
For example, I have a an array:
User = array(
fname => "Joe"
lname => "Schmidt"
)
with a User table in my database with columns id, fname and lname. One of the options is creating an object and doing:
$user = new User;
$user->fname = User['fname'];
$user->lname = User['lname'];
$user->save();
However, this seems like so much code for such common functionality. Is there a way to insert an array into the database where array keys match corresponding columns without me writing my own function or doing some SQL query hack? Ideally it uses the already present Active record of Yii.
What you want to do is handled by the framework itself.
You can mass assign like:
$user->attributes=$_POST['User'];
Read more about Mass Assignment
I have never worked with Yii before, so I can't offer a solution using that, but you can serialize the array and store it in the single cell in your database, like so:
$user = array("fname" => "Joe", "lname" => "Schmidt");
$serialized = serialize($user);
//Store the $serialized variable in the database
When you are ready to access it:
//Get your data from the database
$unserialized = unserialize($usersFromDB);
$fname = $unserialized['fname']; //Joe
Hope that helps.
the function is pretty straightforward, try this:
function insert($table, $fields_values = array())
{
$q1 = join(",", array_keys($fields_values));
$q2 = "'".join("','", array_values($fields_values))."'";
$query = "INSERT INTO $table($q1) VALUES($q2)";
// do your DB insert here
}
The main trick is the array to query conversion using join and array_keys / array_values.
Depending the amount of data in array you can write you own function e.g
a) check this backUpdate , modify it to insert /remove render view option
b) Follow this thread
c) Possible traps when inserting multiple records
d) check this associated SOQ
If you know what you are doing its easy to do , you just need to take care of
validations
records exists in associated tables ( if there is FKey involved )
option d). will be a posssible answer if you have simple inserts ( with no associated tables)
I am trying to implement a very simple search function with PHP in symfony.
Basically I have a form that posts a query and I want to retrieve the items in the database that match the query.
If I have a User table with columns first_name and last_name, I want to be able to retrieve all items that contain a query. For example, if I submit 'a', I will get all names that have an 'a' in them:
Bat Man
Black Beard
Adam West
Mister A
So I know I can get all objects in the table whose first names contain 'a' by specifying criteria:
$c = new Criteria();
$c->add(UserPeer::FIRST_NAME, '%a%', Criteria::LIKE);
$users = UserPeer::doSelect($c);
Is there a way I can pass a variable like $query in the add() function? Can I acquire $query via a form and then pass it as a variable in the add function and get all the objects that contain it? Am I even going about this the right way?
On your form create an input with the id 'query'
<label for="query">Query:</label>
<?php echo input_tag('query') ?>
In the action get the parameter IF the form has been submitted
then pass it into your criteria
if($this->getRequest()->getMethod() == sfRequest::POST)
{
$query = $this->getRequestParameter('query');
$c = new Criteria();
$c->add(UserPeer::FIRST_NAME, '%'.$query.'%', Criteria::LIKE);
$users = UserPeer::doSelect($c);
}