I've searched throughout the internet and mostly answers apply to ZF1.
I'd like to join a subselect query into another select using select objects. It's crucial for me to get whole Select object at the end of multiple such joins.
Code looks like this:
$subSelect = new Select();
$subSelect->from(array('TABLE' => 'SOME_TABLE'));
$subSelect->columns(array('ID'));
$select = new Select();
$select->from(array('SEC_TABLE' => 'SOME_ANOTHER_TABLE'));
$select->join(
array('SUB' => $subSelect),
'SUB.ID = SEC_TABLE.ID',
array(),
$select::JOIN_LEFT
);
It was possible in ZF1 using class Zend_Db_Expr, is there any nice way to this in ZF2?
This is answered here
In ZF2 you can combine two Select object instance using its Select::combine() method.
$select->combine($subSelect);
I tried to use Select::combine() but it is functionality used for things such as UNION or INTERSECT or MINUS - keywords placed between select statements. I need pure JOIN and the problem is that Oracle Adapter in ZF2 overwrites standard approach to processJoins method.
Here is the code from Zend/Db/Sql/Select
protected function processJoins(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null)
{
if (!$this->joins) {
return null;
}
// process joins
$joinSpecArgArray = array();
foreach ($this->joins as $j => $join) {
$joinSpecArgArray[$j] = array();
$joinName = null;
$joinAs = null;
// type
$joinSpecArgArray[$j][] = strtoupper($join['type']);
// table name
if (is_array($join['name'])) {
$joinName = current($join['name']);
$joinAs = $platform->quoteIdentifier(key($join['name']));
} else {
$joinName = $join['name'];
}
if ($joinName instanceof ExpressionInterface) {
$joinName = $joinName->getExpression();
} elseif ($joinName instanceof TableIdentifier) {
$joinName = $joinName->getTableAndSchema();
$joinName = ($joinName[1] ? $platform->quoteIdentifier($joinName[1]) . $platform->getIdentifierSeparator() : '') . $platform->quoteIdentifier($joinName[0]);
} else {
if ($joinName instanceof Select) {
$joinName = '(' . $this->processSubSelect($joinName, $platform, $driver, $parameterContainer) . ')';
} else {
$joinName = $platform->quoteIdentifier($joinName);
}
}
$joinSpecArgArray[$j][] = (isset($joinAs)) ? $joinName . ' AS ' . $joinAs : $joinName;
// on expression
// note: for Expression objects, pass them to processExpression with a prefix specific to each join (used for named parameters)
$joinSpecArgArray[$j][] = ($join['on'] instanceof ExpressionInterface)
? $this->processExpression($join['on'], $platform, $driver, $this->processInfo['paramPrefix'] . 'join' . ($j+1) . 'part')
: $platform->quoteIdentifierInFragment($join['on'], array('=', 'AND', 'OR', '(', ')', 'BETWEEN', '<', '>')); // on
if ($joinSpecArgArray[$j][2] instanceof StatementContainerInterface) {
if ($parameterContainer) {
$parameterContainer->merge($joinSpecArgArray[$j][2]->getParameterContainer());
}
$joinSpecArgArray[$j][2] = $joinSpecArgArray[$j][2]->getSql();
}
}
return array($joinSpecArgArray);
}
and here from Zend/Db/Platform/Oracle/Select/SelectDecorator which extends standard Select class and is used for Oracle database:
protected function processJoins(PlatformInterface $platform, DriverInterface $driver = null, ParameterContainer $parameterContainer = null)
{
if (!$this->joins) {
return null;
}
// process joins
$joinSpecArgArray = array();
foreach ($this->joins as $j => $join) {
$joinSpecArgArray[$j] = array();
// type
$joinSpecArgArray[$j][] = strtoupper($join['type']);
// table name
$joinSpecArgArray[$j][] = (is_array($join['name']))
? $platform->quoteIdentifier(current($join['name'])) . ' ' . $platform->quoteIdentifier(key($join['name']))
: $platform->quoteIdentifier($join['name']);
// on expression
$joinSpecArgArray[$j][] = ($join['on'] instanceof ExpressionInterface)
? $this->processExpression($join['on'], $platform, $driver, $this->processInfo['paramPrefix'] . 'join')
: $platform->quoteIdentifierInFragment($join['on'], array('=', 'AND', 'OR', '(', ')', 'BETWEEN')); // on
if ($joinSpecArgArray[$j][2] instanceof StatementContainerInterface) {
if ($parameterContainer) {
$parameterContainer->merge($joinSpecArgArray[$j][2]->getParameterContainer());
}
$joinSpecArgArray[$j][2] = $joinSpecArgArray[$j][2]->getSql();
}
}
return array($joinSpecArgArray);
}
As standard Select class allows you to join another Select ( line : if ($joinName instanceof Select) {), Oracle extended version doesn't.
Is it just a bug in Zend?
Is there any way around it?
It's not in any way connected to Oracle specification, why is it so then?
Related
I was getting the relationship as in laravel 5.3 and was working fine:
//execute the relation of the given model
$data = $model->{$info["relation"]}();
// get the type of the relation
$class = get_class($data);
$dataType = explode("\\", $class);
$relationType = end($dataType);
$options["columns"][$key]["relationType"] = $relationType;
// if its a simple belongs-to statement
if($relationType == "BelongsTo") {
// get all belongs-to query info
$otherTable = $data->getRelated()->getTable();
$foreignKey = $data->getQualifiedForeignKey();
$otherKey = $data->getOtherKey();
// manually join using it
$retrievedRecords->leftJoin($otherTable . ' as ' . $info["relation"], $info["relation"] . '.' . $otherKey, '=', $foreignKey);
} else if($relationType == "HasMany" || $relationType == "HasOne") {
// get all has-many query info
$otherTable = $data->getRelated()->getTable();
$foreignKey = $data->getPlainForeignKey();
$parentKey = $data->getQualifiedParentKeyName();
// manually join using it
$retrievedRecords->leftJoin($otherTable . ' as ' . $info["relation"], $info["relation"] . '.' . $foreignKey, '=', $parentKey);
}
Now i downloaded fresh laravel 5.4 and it gives me error :
Call to undefined method Illuminate\Database\Query\Builder::getOtherKey()
As the getOtherKey() exists in the above code in if() section.
Is there any alternative for that ?
The getOtherKey method has been renamed to getOwnerKey. So you can get the owner key by saying:
$ownerKey = $data->getOwnerKey();
I want to query dynamically based on payload(json) from database.
Example:
$data = [{"key":"age","relation":">","value":"15"},{"operator":"OR"},{"key":"age","relation":"<=","value":"20"}]
I want to do query based on that payload.
Right now what I'm doing is:
$query = User::all();
$payload = json_decode($data, true);
foreach($payload as $value){
if ($value['key'] == 'age') {
$query = $query->where('birthday', $value['relation'], Carbon::now()->subYears($value['age'])->format('Y-m-d');)
}
if($value['key'] == 'gender'{
$query = $query->where('gender', $value['relation'], $value['gender']);
}
}
The problem is yes it can work, but I don't think this is best approach. I don't get any solution to use the "operator" key. Operator usage is to change where to orWhere.
Any solution or tips to make it call dynamically like this?. I want my column at DB neat and simple. I can only think this way.
Thanks!
Encountering this problem, I would go with Local Query Scopes. In this approach You create a model method named scopeJson() or whatever you feel better with to handl all conditions inside. I tried to handle most conditions here not only single where and orWhere. I assumed that your payload contains only one builder at a time.
public function scopeJson($query, $json)
{
$wheres = [
'between' => ['whereBetween', 'not' => 'whereNotBetween'],
'null' => ['whereNull', 'not' => 'whereNotNull'],
'or' => ['orWhere', 'not' => 'orWhereNot'],
'in' => ['whereIn', 'not' => 'whereNotIn'],
'and' => ['where', 'not' => 'orWhereNot'],
'raw' => 'whereRaw'
];
$builder = json_decode($json);
if (count($builder) > 0) {
$query->where(
$builder[0]->key,
$builder[0]->relation,
$builder[0]->value
);
// notBetween, notNull, notOr, notIn, notAnd
if (stripos($builder[1]->operator, 'not') !== false) {
$whereCondition = $wheres[strtolower(substr($builder[1]->operator, 3))]['not'];
} else {
$whereCondition = $wheres[strtolower($builder[1]->operator)];
}
if (count($builder[2]) == 3) {
if ($whereCondition == 'whereRaw') {
$query->$whereCondition(implode(" ", $builder[2]));
} else {
// where, whereNot
$query->$whereCondition(
$builder[2]->key,
$builder[2]->relation,
$builder[2]->value
);
}
} elseif (count($builder[2]) == 2) {
// whereBetween, whereNotBetween, where, whereNot
$query->$whereCondition(
$builder[2]->key,
$builder[2]->value
);
} elseif (count($builder[2]) == 1) {
// whereNull, whereNotNull, whereRaw
$query->$whereCondition(
$builder[2]->key ?? $builder[2]->value // PHP 7.0 Null Coalescing Operator
);
}
}
return $query;
}
If this method is defined within your User's model then you can use it this way:
$users = User::json($data)->get();
PS: Although it should work, I didn't test it.
You can do raw query like this.
$data = '[{"key":"age","relation":">","value":"15"},{"operator":"OR"},{"key":"age","relation":"<=","value":"20"}]';
$query = "SELECT * FROM tablename WHERE";
$payload = json_decode($data, true);
foreach ($payload as $value) {
if (isset($value['operator'])) {
$query .= " " . $value['operator'];
} else {
if ($value['key'] == 'age') {
$query .= " 'birthday' " . $value['relation'] . " " . Carbon::now()->subYears($value['value'])->format('Y-m-d');
}
if ($value['key'] == 'gender') {
$query .= " 'gender' " . $value['relation'] . " " . $value['gender'];
}
}
}
This results in a query like this :
SELECT * FROM tablename WHERE 'birthday' > 2001-07-02 OR 'birthday' <= 1996-07-02
Of course, you might use printf() for formatting and making this cleaner in some other way but this will get you started hopefully.
You can use a variable function name to add your orWhere logic:
$query = User::all();
$payload = json_decode($data, true);
$function = 'where';
foreach($payload as $value){
if(isset($value['operator'])){
$function = $value['operator'] == 'OR' ? 'orWhere' : 'where';
} else {
if ($value['key'] == 'age') {
$query = $query->$function('birthday', $value['relation'], Carbon::now()->subYears($value['age'])->format('Y-m-d');)
} else {
$query = $query->$function($value['key'], $value['relation'], $value['value']);
}
}
}
As long as your json data doesn't match your database (ie. the json has age but the database has birthday) you will not be able to avoid having that if/else statement. That custom logic will have to remain.
Ultimately this idea is its own limiter because the stored queries will have to represent the current state of the database. This means that the maintenance cost of these queries will be significant the moment data is stored in a different way -- if you changed the column birthday to date_of birth all of your stored queries will break. Avoid this.
Instead this goal is better achieved by storing the queries on the Model using Query Scopes and Relationships. If you still need a dynamic list of requests you can store keywords that are associated with the queries and loop through them.
public function test_passing_string() {
$this - > load - > model(array('registration/Registration_model', 'Jawaban_lab_model'));
$registration = new Registration_model();
$jawaban_lab = new Jawaban_lab_model();
$id = "kuda4";
$jawaban_lab - > load($id); //load jawaban_lab from id
$manualy_written_registration_number = "REG/FM/130102-0001";
echo "registration number from jawaban_lab->registration_number : ".$jawaban_lab - > registration_number
.
"<br> registration number from manualy_written_registration_number : ".$manualy_written_registration_number;
//$registration->load($jawaban_lab->registration_number);
$registration - > load($manualy_written_registration_number);
echo "<br> patient id : ".json_encode($registration - > PatientID);
}
Before go to the question, I will explain my code.
On test_passing_string() function, I call 2 model, and create object for each model there are $registration and $jawaban_lab.
To load data from model I create a load() function. load() has two parameters: column_value and column_name. The default value for column_name is that model's Primary Key.
BUT
The problem comes from
$registration->load($jawaban_lab->registration_number);
I can't retrieve any $registration object data, then I test it by passing the value manually by write this:
$manualy_written_registration_number = "REG/FM/130102-0001";
$registration - > load($manualy_written_registration_number);
And the result appear, doesn't that mean my load() function is fine?
Then I check value inside $jawaban_lab->registration_number by echoing it, surprisingly it display same value as my $manualy_written_registration_number variable.
This is screenshoot in my browser when I run test_passing_string() function:
Using $manualy_written_registration_number value
Using $jawaban_lab->registration_number value
Why can't I use the value from
$jawaban_lab->registration_number even though it has the same value as
my manually writen registraiton number?
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
I use multiple database using CodeIgniter 3, registration_model from SQL server and jawaban_lab from MySQL, jawaban lab have column registration_number to store registration_model primary key
var_dump
First of all thanks to rlanvin and Nirajan N Raju
from rlanvin's comment, i find out the problem is come from codeigniter's query helper, because when i enable codeigniter profiling sql server query return "SELECT CASE WHEN (##OPTIONS | 256) = ##OPTIONS THEN 1 ELSE 0 END AS qi"
so i think codeigniter might be cannot generate query so i create the query manually
i change
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
to this
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $column_name . " LIKE '" . trim($column_value) . "'");
} else {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $this::DB_TABLE_PK . " LIKE '" . trim($column_value) . "'");
}
if ($query->row()) {
$this->populate($query->row());
}
}
So, I am building myself a simple(ish) datagrid class for my CodeIgniter app.
What I am wondering is, I have some columns that I would like to "format" in that I mean, some may contain only a 1 or a 0, yet I want to turn them into a Yes or No respectively.
How can I do this? In other words, I want to be able to pass in another parameter..something like:
$this->_columnCallBack pass it an array like array(column_number=>'NameOfCallBackFunction')
I am assuming that I would do it somewhat like I did the _columnclass, where I pass in the column number, and the class as an array... but I don't know how I would get the function to fire off to do the replacement...
Code
class O7thDG {
public function __construct($params){
$this->_table = $params['table'];
$this->_pk = $params['pk'];
$this->_fields = (isset($params['fields'])) ? $params['fields'] : null;
$this->_where = (isset($params['where'])) ? $params['where'] : null;
$this->_order = (isset($params['order'])) ? $params['order'] : null;
$this->_extras = (isset($params['extras'])) ? $params['extras'] : null;
$this->_add = (isset($params['add'])) ? $params['add'] : FALSE;
$this->_edit = (isset($params['edit'])) ? $params['edit'] : FALSE;
$this->_delete = (isset($params['delete'])) ? $params['delete'] : FALSE;
$this->_editlink = (isset($params['editlink'])) ? $params['editlink'] : null;
$this->_deletelink = (isset($params['deletelink'])) ? $params['deletelink'] : null;
$this->_editlinkextras = (isset($params['editlinkextras'])) ? $params['editlinkextras'] : null;
$this->_deletelinkextras = (isset($params['deletelinkextras'])) ? $params['deletelinkextras'] : null;
$this->_tableid = (isset($params['tableid'])) ? $params['tableid'] : null;
$this->_tableclass = (isset($params['tableclass'])) ? $params['tableclass'] : null;
$this->_columnclass = (isset($params['columnclass'])) ? $params['columnclass'] : null;
$this->_includeheader = (isset($params['includeheader'])) ? $params['includeheader'] : TRUE;
$this->_allowpaging = (isset($params['allowpaging'])) ? $params['allowpaging'] : FALSE;
$this->_sorting = (isset($params['sorting'])) ? $params['sorting'] : null;
$this->_columncallback = (isset($params['columncallback'])) ? $params['columncallback'] : null;
}
public function BuildIt($responsive = TRUE){
$_ci =& get_instance();
$_ci->load->database();
$_ci->load->library('table');
$_ci->load->library('TKCommon', null, 'comm');
$fldlist = $this->_buildSelectFieldList();
$_ci->db->select($fldlist);
$cols = $this->_buildColumnFieldList();
$ret = '';
if($this->_where != null){
// build the where
}
if($this->_order != null){
// build the order
}
if($this->_extras != null){
// build the extras
}
// Query the specified table
$qry = $_ci->db->get($this->_table);
if($cols == null){
$cols = $_ci->db->list_fields($this->_table);
$fldlist = $cols;
}else{
$fldlist = explode(', ', $fldlist);
}
if($qry){
// throw the results into an associative array
$rs = $qry->result_array();
if($rs){
$rCt = count($rs);
$cCt = $qry->num_fields();
// add our responsive wrapper
if($responsive){
$ret .= '<div class="table-responsive">';
}
// fire up our table
$tid = '';
$tc = '';
if($this->_tableid != null){$tid = ' id="' .$this->_tableid . '"';}
if($this->_tableclass != null){$tc = ' class="' .$this->_tableclass . '"';}
$_ci->table->set_template(array('table_open'=>'<table' . $tid . $tc . '>'));
// build our header row, but only if we need to
if($this->_includeheader && $cCt > 0){
// see if we need to include the admin column
if($this->_edit || $this->_delete){
$_ci->table->set_heading(array_merge($cols, array('Admin')));
}else{
$_ci->table->set_heading($cols);
}
}
// build each records row
for($r = 0; $r < $rCt; ++$r){
$ca = array();
for($c = 0; $c < $cCt; ++$c){
if(($this->_columnclass != null) && ($c == key($this->_columnclass))){
// figure out which column needs the class, and what class needs to be applied
$ca[] = $this->_columnCallback($c, array('data'=>$rs[$r][$fldlist[$c]], 'class'=>$this->_columnclass[key($this->_columnclass)]));
}else{
$ca[] = $this->_columnCallback($c, $rs[$r][$fldlist[$c]]);
}
}
// see if we need to include the admin column
if(($this->_edit || $this->_delete) && ($this->_editlink != null || $this->_deletelink != null)){
$txt = '';
if($this->_edit &&($this->_editlink != null)){
$txt .= '<span class="fa fa-pencil fa-lg"></span> ';
}
if($this->_delete &&($this->_deletelink != null)){
$txt .= '<span class="fa fa-trash-o fa-lg"></span>';
}
if(($this->_columnclass != null) && ($cCt == key($this->_columnclass))){
$ca[] = array('data'=>$txt, 'class'=>$this->_columnclass[key($this->_columnclass)]);
}else{
$ca[] = $txt;
}
}
$_ci->table->add_row($ca);
}
$ret .= $_ci->table->generate();
// close our responsive wrapper
if($responsive){
$ret .= '</div>';
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
}else{
$ret .= $_ci->comm->ErrorBox('There was an issue running the query, please make sure at least your primary key, and table are correct.');
}
return $ret;
}
// build our select's field list
private function _buildSelectFieldList(){
if($this->_fields == null){
return '*';
}else{
$flds = array_map(function($item){return $item['field'];}, $this->_fields);
return implode(', ', $flds);
}
}
// build our tables column list
private function _buildColumnFieldList(){
if($this->_fields == null){
return null;
}else{
return array_map(function($item){return $item['label'];}, $this->_fields);
}
}
private function _columnCallback($col, $val){
if($this->_columncallback != null){
if($col == key($this->_columncallback))
return $this->_columncallback[key($this->_columncallback)]($val);
}else{
return $val;
}
}
}
and my external function that I may want to use is simply:
// Format boolean value to Yes or No
public function YesNo($val){
return ((bool)$val) ? 'Yes' : 'No' ;
}
CI Documentation for the table class has $this->table->function, however, the function(s) passed applies to the entire table
What about using and/or anonymous functions:
http://docs.php.net/manual/es/function.func-get-args.php
http://php.net/manual/en/functions.anonymous.php
Update 2 "reloaded"
You could also check grocery crud, it's CI library and do some interesting things that can be useful for you project:
http://www.grocerycrud.com/
Grocery crud uses call_user_func from PHP and allows you to use any function declaread in your controller, if this is what you need then it's just matter of time and check grocery crud code.
In the library a protected property is declared for each callback for example (line #3386 v1.4.1):
/* Callbacks */
protected $callback_before_insert = null;
So you/me/any can set the callback function in case is needed, then check for any callback setted doing something like (line #878 GroceryCrud 1.4.1):
if($this->callback_before_insert !== null)
{
$callback_return = call_user_func($this->callback_before_insert, $post_data);
if(!empty($callback_return) && is_array($callback_return))
$post_data = $callback_return;
elseif($callback_return === false)
return false;
}
Of course there's a method to set the callback (line #4518 from v1.4.1):
public function callback_before_insert($callback = null)
{
$this->callback_before_insert = $callback;
return $this;
}
And the user/dev set the callback doing:
$crud->callback_before_insert(array($this,'my_callback'));
And/Or this technique allows you use something like:
$this->load->model('Customers');
$crud->callback_before_insert(array($this->Customers,'getCustomersCallback'));
even if you're usign php 5.3 or greater you can use an anonymous method:
$crud->callback_before_insert(function($post_array){
$post_array['user_id'] = $this->session->userdata('user_id');
return $post_array;
});
More info: http://www.grocerycrud.com/documentation/tutorial_using_callbacks
About Grocery Crud:
Author: John Skoumbourdis (more about author/library)
Web: GroceryCrud
License: released with dual licensing, using the GPL v3 and the MIT license.
Update 3
Update I've read more carefully your question, thinking functions varible can work for you:
http://php.net/manual/es/functions.variable-functions.php
See the first and second samples here: http://www.php.net/manual/en/language.oop5.php
Still don't know if they will work "outside" your class, but it could.
These functions will work as you want to, but you need to rewrite a bit for your needs.
function callback1($array, $row_id, $function)
{
if(function_exists($function))
return $function($array[$row_id]);
else
return 0;
}
function YesNo($val)
{
return intval($val) ? 'Yes' : 'No' ;
}
#example of array and usage of script.
$array = array('id' => '0', 'id2' => '1');
$ok = callback1($array, 'id2', 'YesNo');
Make filters array
$this->filters = ['column_name' => 'function_name', 'column_name2' => 'otherFunction'];
Then you just apply the filter to the data
if ( array_key_exists($column_name, $this->filters) ) {
// Add row that contains filtered data
$row_data = $this->filters[$column_name]($column_val);
}else{
$row_data = $column_val;
}
If your functions aren't available globally (not in a helper or built-in php), you'll have to use something like this:
call_user_func(array($this, $this->filters[$column_name]), $column_val);
OR
$this->{$this->filters[$column_name]}($column_val);
This would run a function from inside the library O7...
One of my project use solr1.2 and when i use "sort by score" in search function it's not working.I don't know why?
Can any one explain this.I am totally confuse.
my controller where i do :
protected function globalSearch($searchTerm, $productFilter = array())
{
$solrService = $this->get('syd.solr_service');
$solrQuery = new SolrQuery('*:*');
$solrQuery->addField('id')
->addField('first_product_slug')
->addField('first_product_name')
->addField('name')
->addField('slug')
->addField('thumbnail_path')
->addField('product_slug')
->addField('design_category_id')
->addSortField('score', SolrQuery::ORDER_DESC);
$solrQuery->set("group", "true");
$solrQuery->set("group.field", "first_product_id");
$solrQuery->set("group.limit", 4);
if($searchTerm){
$filterQueries = array();
$searchTerms = explode(' ',$searchTerm);
$searchTerms[] = $searchTerm;
$searchTerm = '("' . implode('" OR "', $searchTerms) . '")';
$filterQuery = sprintf(self::SEARCH_STRING, $searchTerm);
$solrQuery->addFilterQuery($filterQuery);
}
if (!empty($productFilter))
{
$productFiltersArr = array();
$productFilterQry = '';
foreach ($productFilter as $productFilterValue )
{
$productFiltersArr[] = 'first_product_slug:' . $productFilterValue;
}
$productFilterQry = implode(' OR ', $productFiltersArr);
$solrQuery->addFilterQuery($productFilterQry);
}
$solrQuery->setRows(1000);
try {
$solrObject = $solrService->query(
'SydPrintBundle:DesignTemplate',
$solrQuery,
SolrService::WRITER_FORMAT_SOLR_OBJECT
);
$templates = $solrObject->offsetGet('grouped')->offsetGet('first_product_id')->offsetGet('groups');
}
catch (\Exception $e) {
$templates = array();
}
if (!$templates) {
if (!empty($searchTerm)) {
$this->setFlash('catalog-message', 'No results found for your search.');
}
return array();
}
if (!$searchTerm) {
if (!empty($searchTerm)) {
$this->setFlash('catalog-message', 'No results found for your search.');
}
return array();
}
return $templates;
}
When you say when i use "sort by score" in search function it's not working I assume you are telling that the results are not sorted by score.
This is because your main query is *:* and you are adding your search terms via a filter query, which won't influence the score. See https://wiki.apache.org/solr/CommonQueryParameters#fq where it says
This parameter can be used to specify a query that can be used to restrict the super set of documents that can be returned, without influencing score.
So if you make the search term filter query as your main query, then you should see results sorted by score.
Update:
Instead of
$solrQuery = new SolrQuery('*:*');
use
$solrQuery = new SolrQuery();
and instead of
$solrQuery->addFilterQuery($filterQuery);
use
$solrQuery->setQuery($filterQuery);